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

查看:100
本文介绍了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!

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

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