繁体   English   中英

更改二维int值的“索引超出了数组的范围”

[英]'Index was outside the bounds of the array' changing 2D int values

我是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;

有想法该怎么解决这个吗?

更改

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM