C# 'Index was outside the bounds of the array.' 用于一个数组而不是另一个

C# 'Index was outside the bounds of the array.' for one array but not another

我有 2 个数组用于存储来自用户的 2 个系列的输入。我将两个数组的边界设置为等于同一个变量,但是在输入信息时,在第一个数组的最终输入之后,我得到一个异常 'Index was outside the bounds of the array.'.

当我尝试将数组的边界更改为常量时,它们表现正常。

            string[] names = new string[movies-1];
            double[] ratings = new double[movies-1];
            for(int i = 0; i < movies; i++)
            {
                names[i] = Console.ReadLine();
                ratings[i] = Convert.ToDouble(Console.ReadLine());
            }

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

你只差一(两次)-

  1. 数组应实例化为 movies 的长度,而不是 movies-1

  2. 迭代时,你希望i最多等于movies-1,因为数组赋值是从0开始的。

考虑一下 - 如果 movies 等于 1(一部电影),您当前正在实例化一个具有 0 个槽的数组 - 您尝试访问的任何索引都将超出范围。

C# 展示了基于零的索引。也就是说,大小为 s 的数组的元素索引范围为 0s - 1.

由于您声明数组 names 的大小为 movies - 1,因此其元素的索引范围为 0movies - 2。因此,循环:

for(int i = 0; i < movies; i++)
{
    names[i] = Console.ReadLine();
    ratings[i] = ...
    ...
i = movies - 1.

时,

将尝试访问数组 namesratings 中的越界索引

您应该将数组声明为:

string[] names = new string[movies];
double[] ratings = new double[movies];

以便它们与您的 for 循环定义一致。