求矩阵的两对角线上的元素之和

/*题目描述
求矩阵的两对角线上的元素之和
输入
矩阵的行数N
和一个N*N的整数矩阵a[N]N
输出
所输矩阵的两对角线上的元素之和
样例输入
3
1 2 3
4 5 6
7 8 9
样例输出
25*/

import java.util.*;

public class Text_1138 {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int sum = 0;
    int[][] a = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            a[i][j] = sc.nextInt();
            if (i == j || i+j+1==n) {//对角线的索引规律
                sum = sum + a[i][j];
            }
        }
    }
    System.out.println(sum);
}
}

猜你喜欢

转载自blog.csdn.net/cwj_ya/article/details/82593375