【发布时间】:2020-11-07 02:48:19
【问题描述】:
在下面的 C# 代码中,我想创建一个大小为 [5,2] 的二维数组。 如果我理解正确的话,应该是这样的:
0 1 2
0[0,0] [0,1] [0,2]
1[1,0] [1,1] [1,2]
2[2,0] [2,1] [2,2]
3[3,0] [3,1] [3,2]
4[4,0] [4,1] [4,2]
但是为什么我的程序会抛出一个
IndexOutOfRangeException
...?
using System;
namespace program {
class program{
Random random = new Random();
int[,] board = new int[5,2];
public program(){
Print2DArray(randomBoard(0.5,board));
}
public int[,] randomBoard(double chance, int[,] board){
int[,] temp = board;
for(int y = 0; y < board.GetLength(1); y++){
for(int x = 0; x < board.GetLength(0); x++){
if(random.NextDouble() <= chance){
board[y,x] = 1;
} else {
board[y,x] = 0;
}
}
}
return temp;
}
public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j] + "\t");
}
Console.WriteLine();
}
}
static void Main(string[] args){
program program1 = new program();
}
}
}
【问题讨论】:
-
它是索引超出范围,因为数组从0开始到4结束,this = 5个索引,0、1、2、3、4,如果你想保持相同的代码然后make它 6,2d 部分也是如此
-
对不起,我解释得不好,我现在编辑了。在我的程序中,我使用了
-
我的错,直到那时我才尝试代码。我再看看
-
这不只是因为 for 循环的方式不对吗?现在我实际上在 Visual Studio 中查看它
-
y应该转到board.GetLength(0)而不是GetLength(1)。同样,x也使用了错误的边界。