網上搜索基本都是Java的代碼,大同小異,於是我就寫一個C#版本的,供初學者參考。
如
1 2 3 1 4 7
4 5 6 顯示結果為 2 5 8
7 8 9 3 6 9
這里主要有兩個知識點
0. 首先定義一個二維數組
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
1. 獲取二維數組的行數
arr.GetLength(0)
2.獲取二維數組的列數
arr.GetLength(1)
下面是代碼:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; 6 for (int i = 0; i < arr.GetLength(0); i++) 7 { 8 for (int j = 0; j < arr.GetLength(1); j++) 9 { 10 Console.Write(arr[i, j] + " "); 11 } 12 Console.WriteLine(); 13 } 14 Console.WriteLine(); 15 for (int i = 0; i < arr.GetLength(0); i++) 16 { 17 for (int j = 0; j < arr.GetLength(1); j++) 18 { 19 Console.Write(arr[j, i] + " "); 20 } 21 Console.WriteLine(); 22 } 23 } 24 }