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

#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停留就直接进行下一步,这是怎么回事?
这个是C Prime Plus第六版第七章编程练习第8题

阅读 1.7k
1 个回答

你的问题是在输入缓冲区中遗留了('\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");
}
// ...其他代码...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏