簡體   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