停止用户输入的 while 循环

问题描述 投票:0回答:1

我想计算用户输入的数字的平均值,用户可以输入任意数量的数字,即只有当用户想要时循环才会停止。

为了停止用户输入的循环,我尝试了以下方法:

while (true)
{
    /* code here */
    printf("\nContinue? (Y/N)");
    char res;
    scanf("%c", &res);
    if (res == 'N') {
        break;
    }
}

我期望这样的输出:

Enter number: 32
Continue? (Y/N) Y
Enter number: 78
Continue? (Y/N) N
55.0000

但是我得到了这个输出:

Enter number: 32
Continue? (Y/N)
Enter number: 78
Continue? (Y/N)
Enter number: N
Continue? (Y/N)
62.666668

这是我的完整代码:

#include <stdio.h>
#include <stdbool.h>
int main()
{
    int sum = 0;
    int count = 0;
    while (true) {
        printf("\nEnter number: ");
        int a;
        scanf("%d", &a);
        sum += a;
        count += 1;
        printf("\nContinue? (Y/N)");
        char res;
        scanf("%c", &res);
        if (res == 'N') {
            break;
        }
    }
    float avg = (sum*1.0)/count;
    printf("\n%f", avg);
    
    return 0;
}

我自己尝试了很多方法来解决这个问题,但没有成功。我仍然不确定我的错到底在哪里。请帮我解决这个问题。

c while-loop scanf
1个回答
2
投票

您的终端是行缓冲的,因此输入缓冲区包含一个数字和一个“ '。

scanf("%c", &reas)
将读取换行符。 通过在格式字符串前添加空格“ ”来更改格式字符串以跳过空格:

      scanf(" %c", &res);

和示例运行:

Enter number: 1

Continue? (Y/N)Y

Enter number: 2

Continue? (Y/N)N

1.500000
© www.soinside.com 2019 - 2024. All rights reserved.