2d Array in C# with random numbers

前端 未结 2 1535
灰色年华
灰色年华 2021-01-17 06:38

I want to create 2d array in C#. size: 3 on 5, and insert into random numbers. I try that but it\'s not work:

Random rnd = new Random();
            int[][]          


        
相关标签:
2条回答
  • 2021-01-17 07:23

    Change your array declaration

    int[,] lala = new int[3,5];
    

    and assignment operation

                    lala[i,j]= rnd.Next(1, 10);
    

    to use 2d array syntax of jagged array.

    or if you want to use jagged array, you have to declare only the most outer size in first declaration and then declare the inner size within the loop:

    Random rnd = new Random();
    int[][] lala = new int[3][];
    for(int i=0;i<3;i++)
    {
        lala[i] = new int[5];
        for(int j=0;j<4;j++)
            lala[i][j]= rnd.Next(1, 10);
    }
    

    Update

    Complete codes for jagged array:

    Random rnd = new Random();
    int[][] lala = new int[3][];
    for (int i = 0; i < lala.Length; i++)
    {
        lala[i] = new int[5];
        for (int j = 0; j < lala[i].Length; j++)
            lala[i][j] = rnd.Next(1, 10);
    }
    

    and 2d array

    Random rnd = new Random();
    int[,] lala = new int[3,5];
    for (int i = 0; i < lala.GetLength(0); i++)
    {
        for (int j = 0; j < lala.GetLength(1); j++)
            lala[i,j] = rnd.Next(1, 10);
    }
    
    0 讨论(0)
  • 2021-01-17 07:35

    Here it is:

        Random rnd = new Random();
        int[,] lala = new int[3,5];
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<5;j++)
            {
                lala[i, j]= rnd.Next(1, 10);
                Console.WriteLine("[{0}, {1}] = {2}", i, j, lala[i,j]);
            }
        }
    

    working sample: http://dotnetfiddle.net/4Fx9dL

    0 讨论(0)
提交回复
热议问题