You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过用户输入终止while循环并实现平均值计算?

问题分析与修复:用户输入数字平均值计算的循环终止问题

问题根源

使用scanf("%d", &a)读取整数时,用户输入数字后按下的回车符(\n)会残留在输入缓冲区中。后续的scanf("%c", &res)会直接读取这个换行符,而非用户输入的Y/N。这导致程序跳过了等待用户确认的步骤,直接进入下一次循环,把用户本应输入的Y/N当作新的数字处理,最终计算出错误的平均值。

修复方案

方法一:读取字符前清空缓冲区换行符

在读取确认字符前,用getchar()消耗掉缓冲区里的换行符:

#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)");
        // 清除缓冲区残留的换行符
        getchar();
        char res;
        scanf("%c", &res);
        if (res == 'N' || res == 'n') { // 兼容小写n,提升友好性
            break;
        }
    }
    float avg = (sum * 1.0) / count;
    printf("\n%.4f", avg); // 控制输出四位小数,匹配预期格式
    
    return 0;
}

方法二:在scanf格式串前添加空格

格式串前的空格会自动跳过所有空白字符(包括换行、空格、制表符),避免读取到残留的换行符:

#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;
        // 空格跳过所有空白字符,直接读取用户输入的Y/N
        scanf(" %c", &res);
        if (res == 'N' || res == 'n') {
            break;
        }
    }
    float avg = (sum * 1.0) / count;
    printf("\n%.4f", avg);
    
    return 0;
}

额外优化

  • 增加对小写n的判断,让用户输入更灵活
  • 使用%.4f格式化输出,使结果与预期的55.0000格式一致

内容的提问来源于stack exchange,提问作者S Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 12:41:07