求一個3*3矩陣對角線元素之和
阿新 • • 發佈:2018-11-26
public static void main(String[] args) { int[][] a = new int[][] { { 100, 2, 5 }, { 4, 7, 6 }, { 17, 8, 9 } }; matrSum(a); } /*100 2 5 0 (0) (1) (2) 4 7 6 1 (0) (1) (2) 17 8 9 2 (0) (1) (2) */ private static void matrSum(int[][] a) { int sum1 = 0; int sum2 = 0; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) { if (i == j) { sum1 += a[i][j]; } if (j == a.length - i - 1) { sum2 += a[i][j]; } } System.out.println("矩陣對角線之和分別是:" + sum1 + "和" + sum2); }