【发布时间】:2019-03-20 16:05:18
【问题描述】:
我目前被困在我需要完成的任务的一小部分。 作业的一项要求是
“调用一个函数,提示用户输入二次方程的系数 a、b 和 c 的每个值,并返回输入的值,并检查有效输入的错误(scanf 返回一个值)。”
我不知道该怎么做。我可以很容易地提示用户输入,我可以检查它是否是有效的输入,但我不知道如何把它变成一个函数。我当前的代码是:
{
if (isalpha(a))
{
printf("INPUT ERROR!\n");
printf("Enter a value for a: ");
scanf("%d", &a);
}
} //this is how I would normally check the input
int main(void) //start of main() function definition
{
int a, b, c, n, D; //declares integer variables a, b, c, n, and D
float root1, root2; //declares float variables root1 and root2
do //do while loop starts here
{
printf("Enter a value for a: "); //prompts user to input integer for variable 'a'
scanf("%d", &a); //reads an integer from the keyboard and stores in the variable 'a'
printf("%d\n", a); //returns value of integer that was input for variable 'a'
printf("Enter a value for b: "); //prompts user to input integer for variable 'b'
scanf("%d", &b); //reads an integer from the keyboard and stores in the variable 'b'
printf("%d\n", b); //returns value of integer that was input for variable 'b'
printf("Enter a value for c: "); //prompts user to input integer for variable 'c'
scanf("%d", &c); //reads an integer from the keyboard and stores in the variable 'c'
printf("%d\n", c); //returns value of integer that was input for variable 'c'
...}
对于任何格式错误,我深表歉意,但这基本上是我坚持使用的程序的一部分。
我的问题是,我怎样才能将第一个函数与 do/while 循环中的所有内容结合起来,以创建一个可以调用 3 次的大函数?
我不知道如何使用函数将 a 的所有实例切换为 b 和 c,因为我以前从未真正使用过这样的函数。
【问题讨论】:
-
“对有效输入的错误检查”可能包括以下问题:非数字“xyz\n”、空“\n”、额外的“123 xyz\n”、溢出“12345678901234567890\n” ,文件结尾,尾随空格“ 123 \n”等。代码取决于您想要的输入的干净程度以及如何处理错误的输入。
标签: c function methods do-while