如何解决C#2DArray IndexOutOfBound,为什么?
在下面的C#代码中,我想创建一个大小为[5,2]的2D数组。 如果我正确理解,应该看起来像这样:
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();
}
}
}
解决方法
在您的代码中,y
从0
到维度 1
中的元素数
而x
转到0
到维度 0
但是,在您的for
循环中,似乎已经交换了尺寸,
board [y,x] = 1; //将其更改为板[x,y] = 1;
类似地,对于else
条件,它应该是board [x,y] = 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。