【发布时间】:2016-09-11 05:47:13
【问题描述】:
所以我在我的 C 程序中使用了 Visual Studio。
while 循环以提示和 scanf 开始,如果用户输入非数字响应,则循环中的 switch/case 将变为默认值。这会打印一个错误并“继续”循环。
问题在于,当循环继续到下一次迭代时,它会完全跳过“scanf”,然后无限循环默认情况。我已经搜索了几个小时,但似乎找不到解决方案。
我的目标是跳过 switch/case 之后的代码,然后回到开头。任何帮助将不胜感激。
while (userInput != 'N' && userInput != 'n') {
printf("Enter input coefficients a, b and c: "); // prompt user input
scanf_s("%d %d %d", &a, &b, &c); // look for and store user input
/* ----- Break up the quadratic formula into parts -----*/
inSqRoot = (pow(b, 2) - (4.0 * a * c)); // b^2 - 4ac
absInSqRoot = abs((pow(b, 2) - (4.0 * a * c))); // absolute value of b^2 - 4ac
denom = 2.0 * a; // get denomiator 2.0 * a
negB = -1.0 * b; // take negative of b
/*------ Determine number of roots -------*/
if (!isdigit(a) || !isdigit(b) || !isdigit(c)) {
rootNum = 4;
} // end if
else if (a == 0 && b == 0 && c == 0) {
rootNum = 0;
} // end if
else if (inSqRoot == 0) {
rootNum = 1;
} // end if
else if (inSqRoot > 0) {
rootNum = 2;
} // end if
else if (inSqRoot < 0) {
rootNum = 3;
} // end if
/*------ Begin switch case for rootNum ------*/
switch (rootNum) {
case 0: // no roots
printf("The equation has no roots.\n");
break;
case 1: // one root
root1 = (-b + sqrt(inSqRoot)) / denom;
printf("The equation has one real root.\n");
printf("The root is: %.4g\n", root1);
break;
case 2: // two roots
root1 = (-b + sqrt(inSqRoot)) / denom;
root2 = (-b - sqrt(inSqRoot)) / denom;
printf("The equation has two real roots.\n");
printf("The roots are: %.4g and %.4g\n", root1, root2);
break;
case 3: // imaginary roots
printf("The equation has imaginary roots.\n");
printf("The roots are: %.1g + %.4gi and %.1g - %.4gi \n", negB / denom, sqrt(absInSqRoot) / denom, negB / denom, sqrt(absInSqRoot) / denom);
break;
default:
printf("ERROR: The given values are not valid for a quadratic equation.\n");
continue;
}
printf("Enter Y if you want to continue or N to stop the program: ");
scanf_s("%*c%c", &userInput);
printf("\n");
}
【问题讨论】:
-
continue表示“中断当前执行并从头开始循环代码”。所以它是循环的“短路”。另一方面,break将退出循环块。在这里你可以简单地跳过conitinue并且你的scanf_s 将被执行。 -
然而,在
casestatemets 中,break打破了当前case而不是外部循环 -
好吧,如果默认情况被激活,我的目标是跳过 switch case 之后的代码。然后回到顶部,要求用户重新输入整数值。
-
scanf_s("%d %d %d", &a, &b, &c);导致输入被读取为整数而不是 ascii 字符。所以调用isdigit(a)没有意义,因为a不是ASCII 字符。例如,如果用户输入“1”,那么a的值将是 1 而不是 31('1'的 ascii 字符)。在这种情况下,isdigit将在您希望它为 true 时返回 false。 -
这听起来像是一个荒谬的问题——但如果我的预感是正确的,那么它很快就会变得有意义。你有多确定 scanf_s 没有被调用?当您陷入无限循环时,您是否会偶然看到“输入输入系数 a、b 和 c:”重复打印?
标签: c