第二个Scanf in循环没有被读取。跳转到else条件

时间:2015-11-04 02:42:50

标签: c loops if-statement switch-statement

#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", &pounds);
            if (pounds > 0) {
                subT = price * pounds;
                totalP += pounds;
                totalSub += subT;
            }
            else {
                printf("1st");
            }
        }
        else {
            printf("2nd");
        }

    }

我不明白为什么我会收到这个逻辑错误。当用户输入项目时,我向用户询问另一个输入,即项目的“磅数”。但我不知道为什么它会进入打印出“第二”的最后一个条件。任何人都可以解释发生了什么。我最初也尝试使用开关,但同样的问题也出现了。

case 'A':
        case 'a':
            price = A_P;
            printf("Please enter the amount in pounds.(lb)");
            scanf("%f", &pounds);
            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);

1 个答案:

答案 0 :(得分:0)

这里的问题是循环的第二次迭代中的scanf()是"消耗"第一次迭代中的\n。这就是为什么scanf()不会第二次提示您并自动转到第二个"条件。 chux是对的 - 您可以通过在%c

之前添加空格来解决此问题
scanf(" %c", &item);

有关详细信息,请参阅此主题:Using the scanf function in while loop

旁注:看起来你并没有在任何地方声明price变量。您还应该使用%lf而不是%f来获取双倍的scanf()