2d Array in C# with random numbers

前端 未结 2 1536
灰色年华
灰色年华 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);
    }
    

提交回复
热议问题