【发布时间】:2021-12-01 13:28:17
【问题描述】:
我正在编写一个程序,它将采用一个锯齿状数组并打印所述锯齿状数组。我使用了一个 foreach 循环来尝试打印数组。每当我去运行程序并查看 Jagged 数组是否会打印它时都会失败。我还尝试了一个 for 循环来打印数组。每次我去运行程序时,我都会抛出 System.IndexOutOfRange。 “对于我的 for 循环,索引超出了数组的范围。我尝试将循环注释掉,当我尝试调用 min 和 max 方法时,它会做同样的事情。
static void Main(string[] args)
{
const int NUMBER_OF_CITIES = 9;
int i;
int[][] miles = new int[NUMBER_OF_CITIES][];
miles[0] = new int[1] { 0 };
miles[1] = new int[1] { 290 };
miles[2] = new int[2] { 373, 102 };
miles[3] = new int[3] { 496, 185, 228 };
miles[4] = new int[4] { 193, 110, 208, 257 };
miles[5] = new int[5] { 214, 90, 165, 270, 73 };
miles[6] = new int[6] { 412, 118, 150, 81, 191, 198 };
miles[7] = new int[7] { 222, 86, 173, 285, 41, 34, 201 };
miles[8] = new int[8] { 112, 207, 301, 360, 94, 155, 288, 141 };
miles[9] = new int[9] { 186, 129, 231, 264, 25, 97, 194, 66, 82 };
int index = 0;
foreach (int[] milesRows in miles)
{
Console.Write("\t" + ++index);
for (int j = 0;j < milesRows.Length; j++)
{
Console.Write(milesRows[j] + "\t");
}
Console.WriteLine();
}
Min(miles[7]);
Max(miles[7]);
Console.WriteLine("The clossest is: " + Min(miles[7]));
Console.WriteLine("The farthest is: " + Max(miles[7]));
}
【问题讨论】:
-
miles[9] = new int[9]...这行导致问题...您创建了长度为 9 的miles。这意味着数组的索引可以从 0 到 8。尝试删除miles[9] = new int[9]...行