【问题标题】:C# 2DArray IndexOutOfBound, Why?C# 2DArray IndexOutOfBound,为什么?
【发布时间】:2020-11-07 02:48:19
【问题描述】:

在下面的 C# 代码中,我想创建一个大小为 [5,2] 的二维数组。 如果我理解正确的话,应该是这样的:

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

【问题讨论】:

  • 它是索引超出范围,因为数组从0开始到4结束,this = 5个索引,0、1、2、3、4,如果你想保持相同的代码然后make它 6,2d 部分也是如此
  • 对不起,我解释得不好,我现在编辑了。在我的程序中,我使用了
  • 我的错,直到那时我才尝试代码。我再看看
  • 这不只是因为 for 循环的方式不对吗?现在我实际上在 Visual Studio 中查看它
  • y 应该转到 board.GetLength(0) 而不是 GetLength(1)。同样,x 也使用了错误的边界。

标签: c# arrays 2d


【解决方案1】:

在您的代码中,y0 变为维度 1 中的元素数 而x0 转换为维度0

中的元素数

但是,在您的 for 循环中,您似乎交换了尺寸,

板[y,x] = 1; // 将其更改为 board [x,y] = 1;

对于else 条件类似,它应该是 board[x,y] = 0

【讨论】:

  • 谢谢!我猜我把这两个弄混了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
相关资源
最近更新 更多