gpt4 book ai didi

c - C 中的多个输入

转载 作者:行者123 更新时间:2023-11-30 17:16:18 24 4
gpt4 key购买 nike

我正在尝试创建一个函数来获取电阻值的多个输入。在我的主函数中,程序要求用户询问需要多少个电阻。用户需要的电阻数量将成为程序要求用户输入电阻值的次数。问题是我应该使用什么循环来发出错误语句并使用户再次输入该值。输入仅接受整数。这是代码:

    #include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

#define MAXSIZE 500
int resistors(int rescount, int *val_res);
int validate ( char *a )
{
unsigned x;
for ( x = 0; x < strlen ( a ); x++ )
if ( !isdigit ( a[x] ) )
return 1;
return 0;
}

int main()
{
int numres;
int resistance[MAXSIZE];
char resist[MAXSIZE];
do
{
printf("How many resistors do you want to place in the circuit?\n");

if (fgets(resist, sizeof(resist), stdin) != NULL)
{
resist[strlen (resist) - 1] = '\0';
if(validate (resist) == 0)
{
numres = atoi(resist);
}
}

} while(numres < 1 || numres > 100);
resistors(numres, resistance);
return 0;
}

int resistors(int rescount, int *val_res)
{
char resistor_value[MAXSIZE];
int z;

printf("Please input the value of resistors:\n");
for(z = 1; z < (*val_res); z++)
{
printf("\tPlease input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}
do{
printf("\tInvalid Resistance\n");
printf("\tRe-input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}

}while(val_res[z-1] < 0);
}
}

输出应该是这样的:

您想在电路中放置多少个电阻?

3

请输入电阻值:

请输入电阻#1:

ABCD

抵抗无效!

重新输入电阻#1:

5

请输入电阻#2:

6

...

等等

这不会发生在我的代码上。请帮忙谢谢!

最佳答案

代码中有两处更改。

第一个,

在循环中,您必须提及 rescount 而不是 *val_res

 for(z = 1; z <= rescount; z++){
. . .
}

然后使用 while 循环代替 do..while 来检查错误。

  while(val_res[z-1] <= 0){
printf("\tInvalid Resistance\n");
printf("\tRe-input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}

}

关于c - C 中的多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com