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

计算用户输入n个数平均值的C代码正负混合输入异常排查

问题分析与修复

原始代码

#include <stdio.h>

int main()
{
    int n;                  //define the type of n numbers
    int array[n];           //define the type of array 
    int sum = 0;            //define and initial the type of sum
    int i;                  //define the type of iterator
    float average = 0.0;    //define the type for average
    
    printf("How many numbers are you going to put? ");    //asks for user input
    scanf("%d", &n);                                        //scans the user input and store it as n
    printf("Enter the numbers: ");
    for (i = 0; i < n; i++) {                         //for loop to get the sum of n numbers
        scanf("%d", &array[i]);
        sum = sum + array[i];
    }
    average = sum / i;                              //averages the n numbers
    printf("Average = %.2f", average);              //prints out the average of n numbers
    return 0;
}

这段C语言代码在仅输入全正数或全负数时可正常运行,但输入正负混合的数值时会出现异常。例如输入40 -5 9时,代码无法正常执行,请问这段代码存在什么问题?


核心问题解析

1. 未初始化变量就创建变长数组

代码中先定义int n;,紧接着用int array[n];创建变长数组,但此时n还未被赋值,内存中是随机垃圾值。这属于未定义行为,之前全正/全负时看似正常只是巧合,程序运行结果完全不可预测。

2. 输入逻辑误解与合法性缺失

你输入40 -5 9时,程序会把第一个值40当作要输入的数字个数n,然后进入循环要求输入40个数字,但你只提供了后续两个值,程序会一直阻塞等待剩余输入,这就是“无法正常执行”的直接原因。同时代码没有对n做合法性检查(比如n必须是正整数),如果输入负数/0,数组创建会直接出错。

3. 整数除法导致平均值计算错误

sum / i中,sum和i都是整数类型,会执行整数除法(丢弃小数部分),之后再转成float类型。比如40 + (-5) + 9 = 44,44 / 3会得到14,转成float后是14.00,但正确平均值应该是约14.67,精度完全丢失。


修复后的代码

#include <stdio.h>

int main()
{
    int n;
    int sum = 0;
    int i;
    float average = 0.0;

    printf("How many numbers are you going to put? ");
    // 检查输入合法性,确保n是正整数
    while (scanf("%d", &n) != 1 || n <= 0) {
        printf("请输入正整数:");
        // 清空输入缓冲区的无效内容
        while (getchar() != '\n');
    }

    // 先获取合法的n,再定义变长数组
    int array[n];

    printf("Enter the numbers: ");
    for (i = 0; i < n; i++) {
        // 确保每个数字输入有效
        while (scanf("%d", &array[i]) != 1) {
            printf("请输入整数:");
            while (getchar() != '\n');
        }
        sum += array[i];
    }

    // 将sum转为float后再做除法,避免整数除法
    average = (float)sum / n;
    printf("Average = %.2f\n", average);

    return 0;
}

内容的提问来源于stack exchange,提问作者Joel Vanta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 11:02:42