while循环中的while循环中 (嵌套两个while循环) 的scanf_s为什么还没进行输入就直接下一步了?

作者站长头像
站长
· 阅读数 16
#include <stdio.h>
#define RATE1 0.15
#define RATE2 0.2
#define RATE3 0.25
int main(void)
{
    float salary = 0; //总工资(含税收
    int hour = 0; //工作小时数
    float tax = 0; //税收
    float income = 0; //收入
    float wage = 0; //基本工资
    int option = 0; //基本工资选项
    char choice; //“是否重新计算”选项


    while (1)
    {
        printf("*****************************************************************\n");
        printf("Enter the number corresponding to the desired pay rate or action:\n");
        printf("1) $8.75/hr            2) $9.33/hr\n");
        printf("3) $10.00/hr            4) $11.20/hr\n");
        printf("5) quit\n");
        printf("*****************************************************************\n\n");
        printf("Enter your option:>");
        scanf_s("%d", &option);
        switch (option)
        {
        case 1:
            wage = 8.75;
            break;
        case 2:
            wage = 9.33;
            break;
        case 3:
            wage = 10.00;
            break;
        case 4:
            wage = 11.20;
            break;
        case 5:
            return 0;
        default:
            printf("Please enter the correct options\n\n");
            continue;
        }
        printf("Enter work-hours:>");
        scanf_s("%d", &hour);
        if (hour > 40)
            salary = hour * wage + (hour - 40) * 1.5 * wage;
        else
            salary = hour * wage;
        if (salary <= 300)
            tax = salary * RATE1;
        else if (salary >= 300 && salary <= 450)
            tax = 300 * RATE1 + (salary - 300) * RATE2;
        else
            tax = 300 * RATE1 + 150 * RATE2 + (salary - 450) * RATE3;
        income = salary - tax;
        printf("SALARY: %f\n   TAX: %f\nINCOME: %f\n\n", salary, tax, income);
        while (1)
        {
            printf("Whether to recalculate<Y/N>:>");
            scanf_s("%c", &choice, 1);
            if (choice == 'N' || choice == 'n')
                return 0;
            else if (choice == 'Y' || choice == 'y')
                break;
            else
                printf("Please enter the correct options\n\n");
        }
    }
    return 0;
}

在最下面这个while循环中,调试时没在scanf_s停留就直接进行下一步,这是怎么回事?while循环中的while循环中 (嵌套两个while循环) 的scanf_s为什么还没进行输入就直接下一步了?这个是C Prime Plus第六版第七章编程练习第8题

回复
1个回答
avatar
test
2024-07-04

你的问题是在输入缓冲区中遗留了('\n')所导致的,参考一下这些修改试试:

// ...其他代码...
while (1)
{
    printf("Whether to recalculate<Y/N>:>");

    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF);

    scanf_s("%c", &choice, 1);
    if (choice == 'N' || choice == 'n')
        return 0;
    else if (choice == 'Y' || choice == 'y')
        break;
    else
        printf("Please enter the correct options\n\n");
}
// ...其他代码...
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容