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

C#新手求助:用户输入数字存数组并控制台输出的代码错误排查

代码存在的3个核心问题

  • 多余的内层for循环逻辑错误:你在每次输入一个数字后,写了j从0到数组长度的循环,会把当前输入的数字覆盖到数组所有已有元素上,最终数组所有值都会等于你最后一次输入的数字。同时循环条件j <= numbers.Length会触发索引越界异常:C#数组索引范围是0 ~ 数组长度-1,等于数组长度的索引是不存在的。
  • 数组赋值索引错位:外层循环的i从1开始计数,而数组索引从0开始,输入的第i个数字应该赋值给numbers[i-1],不需要单独写内层循环。
  • 数组输出逻辑错误:直接调用Console.WriteLine(numbers)只会输出数组的类型名System.Int32[],不会输出数组内的元素,需要遍历数组逐个输出。

修正后可正常运行的代码

using System;

namespace Console_Project_alpha
{
    class Program 
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the amount of numbers: ");
            int amount = Convert.ToInt32(Console.ReadLine());
            
            int[] numbers = new int[amount];
            string nth = "";

            for( int i = 1; i <= amount ; i++)
            {
                if(i == 1)
                {
                    nth = i + "st";    
                }
                else if( i == 2)
                {
                    nth = i + "nd";
                }
                else if( i == 3)
                {
                    nth = i + "rd";   
                }
                else
                {
                    nth = i + "th";
                }
                
                Console.Write("\nEnter " + nth + " Number:");
                int num = Convert.ToInt32(Console.ReadLine());
                // 直接赋值到对应索引位置即可,不需要内层循环
                numbers[i-1] = num;
            }
            
            // 遍历输出数组所有元素
            Console.WriteLine("\n你输入的所有数字如下:");
            foreach (var num in numbers)
            {
                Console.Write(num + " ");
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:57:02