在打印这个锯齿状阵列时,我得到的行数比预期的少1。它应该从第0个索引到第(h-1)个索引开始,创建总共h行。我究竟做错了什么?
h是不。的行。
int h = int.Parse(Console.ReadLine());
int[][] arr = new int[h][];
for(int i = 0; i < h; ++i)
{
arr[i] = new int[i+1];
}
for(int i = 0; i < h; i++)
{
Console.WriteLine();
for(int j = 0; j < i; j++)
{
Console.Write(arr[i][j] + " ");
}
}
那是因为你的内部for循环有条件j < i
。如果第一遍中i
为0,则不会传递内部for循环。
尝试一下
for(int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j] + " ");
}
数组有一个不断增长的元素列表,从1开始,所以如果你想扫描所有项目:
for(int i = 0; i < h; i++)
{
Console.WriteLine();
for(int j = 0; j < (i + 1); j++)
{
Console.Write(arr[i][j] + " ");
}
}
不应该是:
new int[i];
代替:
new int[i+1]
或者是h - 1
?只需更改数组的索引即可。
或者你需要j < arr[i].Length