因此,我正在为我的C程序使用视觉工作室。在while循环中使用“continue”,跳过scanf(“%d”,var)
while循环以提示符和scanf开头,如果用户输入非数字响应,则循环中的开关/情况将变为默认值。这会打印一个错误并“继续”循环。
问题是,当循环继续下一次迭代时,它会完全跳过“scanf”,然后通过默认情况无限循环。我搜索了几个小时,但似乎无法找到解决方案。
我的目标是跳过开关/大小写后的代码,然后回到开头。任何帮助将非常感激。
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");
}
“继续”表示“断开当前执行并从开始启动循环代码”。所以它是循环的“短路”。另一方面,'break'将退出循环块。在这里,你可以简单地跳过'conitinue',你的scanf_s将被执行。 – Antoniossss
然而'case' statemets,'break'打破当前case'不是外部循环 – Antoniossss
那么我的目标是跳过开关案例后的代码,如果默认情况下被激活。然后回到顶部并要求用户重新输入整数值。 – Abbie