“边[]中的索引数量错误,预计'2'”错误

时间:2015-05-20 05:11:17

标签: c#

我一直在尝试按照我编写数组的方式打印此代码,这是一个带有数字的3x3框,我稍后会将其插入其中。一切似乎都正确但我在尝试编写循环时仍然收到此消息:

  

无法将类型'int []'隐式转换为'int [] []'

 static void Main(string[] args)
        {
            Console.Title = "Quadrado Mágico";
            Console.BackgroundColor = ConsoleColor.DarkCyan;
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Random ran = new Random();
            Console.Clear();

            int[][] quadrado = new int [3,3] { { 0, 0, 0 }, 
                                         { 0, 0, 0 },
                                         { 0, 0, 0 } };

             for(int fila = 0; fila < quadrado.Length; fila++) {
                for(int coluna = 0; coluna < quadrado[fila].Length; coluna++) {
                 Console.WriteLine(quadrado[fila][coluna] + "\t");
                 }
                Console.WriteLine();
             }


            Console.ReadKey();
        }

3 个答案:

答案 0 :(得分:2)

此代码有效。您需要将int [] []更改为int [,]

然后,您需要使用GetUpperBound(0)和(1)来获取每个数组的长度。

static void Main(string [] args)         {             Console.Title =“QuadradoMágico”;             Console.BackgroundColor = ConsoleColor.DarkCyan;             Console.Clear();             Console.ForegroundColor = ConsoleColor.DarkBlue;             Random ran = new Random();             Console.Clear();

        int[ , ] quadrado = new int[3, 3] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };

        // ... Loop using the GetUpperBounds.
        for (int fila = 0; fila <= quadrado.GetUpperBound(0); fila++)
        {
            for (int coluna = 0; coluna <= quadrado.GetUpperBound(1); coluna++)
            {
                // Display the element at these indexes.
                Console.WriteLine(quadrado[fila, coluna]);
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }

答案 1 :(得分:0)

std::inner_product

答案 2 :(得分:-1)

更改以下内容

 int[][] quadrado = new int [3,3] { { 0, 0, 0 }, 
                                     { 0, 0, 0 },
                                     { 0, 0, 0 } };

int[,] quadrado = new int[3, 3] { { 0, 0, 0 }, 
                                     { 0, 0, 0 },
                                     { 0, 0, 0 } };