题目描述:
求一个3*3矩阵对角线元素之和
解题思路:
对角线遍历循环
代码:
public class Main { public static void main(String[] args) { int[][] arr = new int[3][3]; int k = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { arr[i][j] = k++; } } int res = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == j) { res += arr[i][j]; } } } System.out.println("结果:" + res); } }