while 循环代码不起作用(keepgoing='y') [英] while loop code not working (keepgoing='y')

查看:74
本文介绍了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);
}

这是运行代码给我的结果:

Here's what running the code gives me:

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!

这篇关于while 循环代码不起作用(keepgoing='y')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆