';索引超出了数组的界限';更改2D int值

本文关键字:更改 2D 界限 int 索引 数组 | 更新日期: 2023-09-27 18:29:29

我对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 ();
    }

我的问题是,每当我更改网格尺寸(将int5更改为其他任何尺寸)时,我都会得到一个错误,即Index was outside the bounds of the array

int width = 5;

int height = 5;

关于如何解决这个问题有什么想法吗?

';索引超出了数组的界限';更改2D int值

更改

int[,] grid = new int[height, width];

int[,] grid = new int[width, height];