while循环代码不起作用(keepgoing ='y')
所以我正在学习如何在C语言中使用while和for循环,但是这段代码似乎无法正常工作. scanf语句似乎被忽略了,循环只是重复自身而无需我输入'Y'使其重复.这是代码:
So I'm learning how to use the while and for loops in C but this code won't seem to work. the scanf statement seems to be getting ignored and the loop just repeats itself without requiring me to input 'Y' for it to repeat. Here's the code:
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);
}
这是运行代码给我的:
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.
它从不提示我输入y,并且代码由于某种原因而退出.
it never prompts me to enter y and the code just exits for some reason.
您遇到的问题是,调用scanf
以使用%c
格式读入值将接受换行符字符作为有效输入!
The problem you're encountering is that the call to scanf
to read in a value using the %c
format will accept a newline character as valid input!
此操作与scanf("%f",&sales);
调用读取float
值但不消耗" 以下换行符的事实结合在一起,会将该换行符保留在输入缓冲区中,例如后续调用以读取keepGoing
的值.因此,您的keepGoing
值为 not y
,程序将终止.
This, combined with the fact that the scanf("%f",&sales);
call reads in a float
value but does not 'consume' the following newline, will leave that newline character in the input buffer, for the subsequent call to read a value for keepGoing
. Thus, you will have a value for keepGoing
that is not y
and the program will terminate.
有几种解决方法.也许最简单的方法是在%c
字段之前添加一个空格字符,这将指示scanf
函数在扫描"输入字符时跳过所有空白"字符(包括换行符):>
There are several ways around this. The simplest, perhaps, is to add a space character before the %c
field, which will instruct the scanf
function to skip all 'whitespace' characters (which includes the newline) when 'scanning' for the input character:
scanf(" %c", &keepGoing); // Added space before %c will skip any 'leftover' newline!