繁体   English   中英

获取索引超出数组的范围

[英]Getting index is outside bounds of the array

有人可以解释为什么我无法做到这一点吗? 这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testing
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            double[] numbers = new double[] { };
            for(int i = 0; i < n; i++)
            {
                var input = double.Parse(Console.ReadLine());
                numbers[i] = input;
            }
            Console.WriteLine(numbers);
        }
    }
}

初始化时数组的长度是固定的。 您的尺寸为0。

double[] numbers = new double[] { };  // { } is the same as 'initialize with 0 elements or no content'

您需要使用列表而不是数组。

List<double> numbers = new List<double>();

for(int i = 0; i < n; i++)
{
   var input = double.Parse(Console.ReadLine());
   numbers.Add(input);
}

您尚未设置数组大小

double[] numbers = new double[n]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM