while 循环代码不起作用(keepgoing='y')

Hel*_*y98 1 c loops scanf while-loop

所以我正在学习如何在 C 中使用 while 和 for 循环,但这段代码似乎不起作用。scanf 语句似乎被忽略了,循环只是重复自己而不需要我输入“Y”来重复。这是代码:

void showCommission();

void main() {
    char keepGoing='y';
    while(keepGoing=='y') {
        showCommission();
        printf("Do you want to calculate another?\n");
        scanf("%c",&keepGoing);
   }
}

void showCommission() {
    float sales,commission;
    const float COM_RATE=0.10;
    printf("Enter the amount of sales\n");
    scanf("%f",&sales);
    commission=sales*COM_RATE;
    printf("The commission is $%f.\n",commission);
}
Run Code Online (Sandbox Code Playgroud)

这是运行代码给我的内容:

Enter the amount of sales                                                                         
5000                                                                                              
The commission is $500.000000.                                                                    
Do you want to calclulate another?    

...Program finished with exit code 10                                                             
Press ENTER to exit console.  
Run Code Online (Sandbox Code Playgroud)

它从不提示我输入 y 并且代码只是出于某种原因退出。

Adr*_*ica 11

您遇到的问题是scanf使用该%c格式读取值的调用将接受换行符作为有效输入!

这与scanf("%f",&sales);调用读入一个float但不“消耗”下一个换行符的事实相结合,将在输入缓冲区中保留该换行符,以便后续调用读取 的值keepGoing。因此,你将有一个值keepGoing不是 y该程序将终止。

有几种方法可以解决这个问题。最简单的可能是在%c字段前添加一个空格字符,这将指示scanf函数在“扫描”输入字符时跳过所有“空白”字符(包括换行符):

scanf(" %c", &keepGoing); // Added space before %c will skip any 'leftover' newline!
Run Code Online (Sandbox Code Playgroud)