计算矩阵的次要元素和主要元素之和?

Calculating sum of secondary and primary elements of matrix?

我正在尝试计算它,但我得到的只是零,我需要计算主要对角线元素和次要对角线元素的总和,然后计算它们总和的绝对差。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int a[][] = new int[n][n];
    int sum=0;
    int i=0;
    int j=0;
    int k=n-1;
    int sum1=0;
    for(i=0; i < n; i++){
        for(j=0; j < n; j++){
            a[i][j] = in.nextInt(); 
        }
    }
        int temp=n;
        int temp2=n;
        while(temp>0 && i<n && j<n)
            {
            sum=a[i][j]+sum;
            temp=temp-1;
            i++;j++;
        }
        while(temp2>0 && i<n && k>=0)
            {
            sum1=a[i][k]+sum1;
            temp2=temp2-1;
            i++; k--;
        }
        int diff=sum-sum1;
        if(diff<0)
            diff=-1*diff;
        System.out.println(diff);
}
}

在第一个for循环之后,i和j都达到了值n。也就是说,i = nj = n。 所以 while 循环不会通过。为避免这种情况,请再次初始化 i 和 j。

i = 0;
j = 0;
while(temp>0 && i<n && j<n)
{
    sum=a[i][j]+sum;
    temp=temp-1;
    i++;j++;
}

i = 0;
while(temp2>0 && i<n && k>=0)
{
    sum1=a[i][k]+sum1;
    temp2=temp2-1;
    i++; k--;
}

备选方案:您可以使代码更简单。

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int a[][] = new int[n][n];
    int sum = 0, sum1 = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            a[i][j] = in.nextInt();

            // primary diagonal
            if (i == j) {
                sum += a[i][j];
            }

            // secondary diagonal
            if (i == n - j - 1) {
                sum1 += a[i][j];
            }
        }
    }
    System.out.println(Math.abs(sum - sum1));
}