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

编写连续相等数字检测C#程序出错,请求错误排查

代码中的错误分析

下面是你的代码存在的几个关键问题:

  • 缺少必要的命名空间引用:使用List<int>需要引入System.Collections.Generic命名空间,否则编译时会提示“List不存在”的错误。
  • 错误地添加循环变量到列表:seq.Add(i);这行代码把循环计数器i添加到了列表,而不是用户输入的数字,完全偏离了需求逻辑。
  • 索引越界异常:当循环第一次执行(i=0)时,访问seq[i-1]等同于访问seq[-1],这会直接抛出索引越界的运行时异常,程序根本无法正常执行到后续逻辑。
  • 输出位置不符合用户认知:输入时提示的位置是从1开始的(比如“position1”),但你输出的equalSeqStart是从0开始的索引值,会让用户混淆位置概念。

修正后的代码示例

using System;
using System.Collections.Generic; // 添加必要的命名空间

public class Exercises
{
    static void Main()
    {
        Console.WriteLine("Insert the length of the sequence of numbers:");
        int n = Convert.ToInt32(Console.ReadLine());
        List<int> seq = new List<int>();
        int equalSeqStart = -1;

        for (int i = 0; i < n; i++)
        {
            Console.WriteLine("Insert the number in position " + (i + 1) + ":");
            // 读取用户输入的数字并添加到列表
            int inputNum = Convert.ToInt32(Console.ReadLine());
            seq.Add(inputNum);
            
            // 只有当i>=1时才进行相邻元素比较,避免索引越界
            if (i >= 1 && seq[i] == seq[i - 1] && equalSeqStart == -1)
            {
                equalSeqStart = i - 1;
            }
        }

        if (equalSeqStart != -1)
        {
            // 转换为从1开始的位置输出
            Console.WriteLine("The sequence of equal numbers starts at position " + (equalSeqStart + 1));
        }
        else
        {
            Console.WriteLine("There is no sequence of equal numbers");
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:34:50