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

C#实现用户输入5个数字求和功能时无法正确计算的问题求助

C#实现用户输入5个数字求和功能时无法正确计算的问题求助

嘿,我瞅了下你这段C#代码,发现两个关键问题导致求和结果不对,咱们一步步来梳理解决:

先贴出你的原始代码方便对照:

static void Main(string[] args)
{
    int[] numbers = new int[5];
    int sum = 0;
    int i;
    Console.WriteLine("Input 5 elements in the array :");
    for (i= 0; i < numbers.Length; i++)
    {
        Console.WriteLine($"element index {i}: ");
        numbers[i] = Convert.ToInt32(Console.ReadLine());
    }
    sum = sum + numbers[i];
    Console.WriteLine("The sum of the elements of the array is " + sum);
    Console.ReadLine();
}

问题分析

  1. 索引越界+求和逻辑位置错误:
    当for循环执行完毕后,变量i的值会变成5(因为循环条件是i < 5,最后一次循环i=4执行完后,i会自增到5,循环终止)。这时候你去访问numbers[i],也就是numbers[5],但你的数组长度是5,合法索引只有0-4,这不仅取不到正确元素,还会直接抛出IndexOutOfRangeException异常。
    而且你现在只在循环结束后加了一次元素,根本没把前面输入的4个数字加到sum里,这肯定得不到正确的总和。

  2. 正确的求和逻辑应该放在循环内部:每次输入完一个数字,就把它加到sum里,这样循环结束后sum就是所有数字的总和。

修正后的代码

static void Main(string[] args)
{
    int[] numbers = new int[5];
    int sum = 0;
    Console.WriteLine("Input 5 elements in the array :");
    for (int i= 0; i < numbers.Length; i++)
    {
        Console.Write($"element index {i}: "); // 用Write代替WriteLine,让输入和提示在同一行,更友好
        numbers[i] = Convert.ToInt32(Console.ReadLine());
        sum += numbers[i]; // 每次输入后直接累加
    }
    Console.WriteLine("The sum of the elements of the array is " + sum);
    Console.ReadLine();
}

测试验证

当你输入如下内容时:

Input 5 elements in the array :
element index 0: 1
element index 1: 1
element index 2: 1
element index 3: 1
element index 4: 1

就能得到预期输出:

The sum of the elements of the array is 5

备注:内容来源于stack exchange,提问作者red

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 06:09:51