實現需求
創建二維數組,數組的列和寬為隨機,數組內的數也是隨機
知識點
1、Random類
Public Random rd = new Random();
int Num_Int = rd.Next(1, 100);
2、數組上下限。
//定義數組
int[] G_Array = new int[1,2,3,4];//一維數組
int[,] G_Array_T = new int[2,3]{{1,2},{3,4},{4,7}};//二維數組
int num1 = G_Array_T.GetUpperBound(0)+1;//二維數組的行數
int num2 = G_Array_T.GetUpperBound(1)+1;//二維數組的列數
關鍵代碼
public int[,] G_Array_int;//定義全局二維數組//隨機生成一個二維數組,二維數組的行數和列數以及數組內的數為隨機Random rd = new Random();private void button1_Click(object sender, EventArgs e){textBox1.Clear();//清空數據DisplayArray();}void DisplayArray(){int[,] G_Array_int = new int[rd.Next(1, 10), rd.Next(1, 10)];//定義一個二維數組label1.Text = string.Format("二維數組行數為{0}行{1}列 ", (G_Array_int.GetUpperBound(0) + 1), G_Array_int.GetUpperBound(1) + 1);//將二維數組的數隨機生成for (int i = 0; i < G_Array_int.GetUpperBound(0) + 1; i++){for (int j = 0; j < G_Array_int.GetUpperBound(1) + 1; j++){G_Array_int[i, j] = rd.Next(1, 100);textBox1.Text += G_Array_int[i, j].ToString() + " ";}textBox1.Text += Environment.NewLine;//換行}}
效果演示
源代碼
運行環境為VS2022