循环中的第二个 Scanf 不是 read.jumps 到 else 条件
2nd Scanf in loop is not being read.jumps to else condition
#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");
}
}
我不明白为什么我会收到这个逻辑错误。当用户输入一个项目时,我要求用户输入另一个输入,即该项目的 "pounds" 。但我不知道为什么它会进入打印出“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()
是第一次迭代中的 "consuming" 中的 \n
。这就是为什么 scanf()
不会第二次提示您并自动转到“第二次”条件的原因。 chux 是对的——您可以通过在 %c
:
之前添加 space 来解决这个问题
scanf(" %c", &item);
有关详细信息,请参阅此线程:Using the scanf function in while loop
旁注:您似乎没有在任何地方声明 price
变量。您还应该使用 %lf
而不是 %f
作为 scanf()
的两倍。
#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");
}
}
我不明白为什么我会收到这个逻辑错误。当用户输入一个项目时,我要求用户输入另一个输入,即该项目的 "pounds" 。但我不知道为什么它会进入打印出“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()
是第一次迭代中的 "consuming" 中的 \n
。这就是为什么 scanf()
不会第二次提示您并自动转到“第二次”条件的原因。 chux 是对的——您可以通过在 %c
:
scanf(" %c", &item);
有关详细信息,请参阅此线程:Using the scanf function in while loop
旁注:您似乎没有在任何地方声明 price
变量。您还应该使用 %lf
而不是 %f
作为 scanf()
的两倍。