c - 循环中的第二个 Scanf 未被读取。跳转到 else 条件

标签 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");
        }

    }

我不明白为什么会出现这个逻辑错误。当用户输入一个项目时,我要求用户提供另一个输入,即该项目的“磅”。但我不知道为什么它会进入最后一个打印出“2nd”的 else 条件。任何人都可以解释发生了什么事。我最初也用开关尝试过,但出现了同样的问题。

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);

最佳答案

这里的问题是,循环的第二次迭代中的 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/

相关文章:

c - 将队列数据结构作为数组实现的问题

loops - 循环 append 几个 .dta 文件

javascript - 添加类不是使用 ClassList.add 列出集合

if-statement - 对 MIPS 中的 if 跳转感到困惑

python - 使用循环或列表理解创建多个 pandas 数据框

java - 如何在 Java 中重复 if 条件?

c - 在 C 中使用 GTK 构建 GUI,使用基本的 Widgets 一切皆有可能吗?或者我应该建立一个自定义的?

c - 释放非 malloc 的内存

c - 链接列表 C 代码挂起而不从 'free-ing' 函数返回

php - foreach 循环未显示所需结果