#include "stdafx.h"
#include "windows.h"
#define A_P 4.55
double pounds;
double subT = 0.0;
double totalP = 0.0;
double totalSub = 0.0;
void main()
{
char item;
while (1) {
printf("Please select your item.\n");
scanf("%c", &item);
if (item == 'a') {
price = A_P;
printf("Please enter the amount in pounds.(lb)");
scanf("%f", £s);
if (pounds > 0) {
subT = price * pounds;
totalP += pounds;
totalSub += subT;
}
else {
printf("1st");
}
}
else {
printf("2nd");
}
}
我不明白为什么会出现这个逻辑错误。当用户输入一个项目时,我要求用户提供另一个输入,即该项目的“磅”。但我不知道为什么它会进入最后一个打印出“2nd”的 else 条件。任何人都可以解释发生了什么事。我最初也用开关尝试过,但出现了同样的问题。
case 'A':
case 'a':
price = A_P;
printf("Please enter the amount in pounds.(lb)");
scanf("%f", £s);
if (pounds > 0) {
subT = price * pounds;
totalP += pounds;
totalSub += subT;
}
else
Beep(500, 500);
break;
...
default:// goes straight to the defualt statement ignores second scanf which reads pounds varaible
printf("That is an invlalid input.\n");
Beep(500, 1000);
最佳答案
这里的问题是,循环的第二次迭代中的 scanf()
正在“消耗”第一次迭代中的 \n
。这就是 scanf()
不会第二次提示您并自动进入“第二”条件的原因。 chux 是对的——您可以通过在 %c
之前添加空格来解决此问题:
scanf(" %c", &item);
有关更多信息,请参阅此线程:Using the scanf function in while loop
旁注:您似乎没有在任何地方声明 price
变量。您还应该使用 %lf
而不是 %f
来执行 scanf()
获取 double 值。
关于c - 循环中的第二个 Scanf 未被读取。跳转到 else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512834/