[英]'Index was outside the bounds of the array' changing 2D int values
I'm quite new to C# and I made this which creates a 5x5 grid which increases each number in the grid by 1
so the grid counts up. 我是C#的新手,我创建了一个5x5网格,该网格将网格中的每个数字加1
因此网格向上计数。
public static void Main () {
int width = 5;
int height = 5;
int gridNumber = 0;
int[,] grid = new int[height, width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (grid [x,y] + (gridNumber +1) < 10){
Console.Write (grid [x,y] + (gridNumber + 1) + " | " );
}
else if (grid [x,y] + (gridNumber +1) == 10) {
Console.Write (grid [x,y] + (gridNumber + 1) + " |" );
}
else {
Console.Write (grid [x,y] + (gridNumber + 1) + " | " );
}
gridNumber++;
}
Console.WriteLine ();
}
Console.ReadKey ();
}
My problem is whenever I change the grid dimensions (changing either int
from a 5
to anything else), I get an error saying Index was outside the bounds of the array
. 我的问题是,每当更改网格尺寸(将int
从5
更改为其他值)时,我都会收到一条错误消息,指出Index was outside the bounds of the array
。
int width = 5;
int height = 5;
Any ideas on how to fix this? 有想法该怎么解决这个吗?
Change 更改
int[,] grid = new int[height, width];
to 至
int[,] grid = new int[width, height];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.