java - 对角差

标签 java arrays for-loop

我在编写对角线差分代码时刚开始编程,我想出了这种方法,

 public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int j = 0;
    int a[][] = new int[n][n];
    int count1 = 0; int count2 = 0;
    int result = 0;
    for(int a_i=0; a_i < n; a_i++){
        for(int a_j = 0;a_j < n;a_j++){
       
            a[a_i][j] = in.nextInt();
        
    }}
    for(int i = 0;i<n;i++)
    {
        count1+=a[i][j];
        System.out.println(count1);
        j++;
    }
    j = 0;
    for(int i = n-1;i>=0;i--)
    {
        count2+=a[i][j];
        System.out.println(count2);
        j++;
    }
    result = Math.abs(count1 - count2);
    System.out.println(result);
}

输入
3
11 2 4
4 5 6
10 8 -12

预期产出 15
我的输出 16

最佳答案

为什么有这么多变通办法? 你需要一个非常小的代码:

for(int i = 0;i<n;i++){
    count1+=a[i][i];
    count2+=a[i][n-1-i];
}

关于java - 对角差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46724424/

相关文章:

algorithm - Matlab For循环只针对矩阵的 "shell"

java - 使用模拟方法参数来模拟后续步骤

C++在网格图中表示相机覆盖区域的最有效方法

ios - 如何将字典转换为数组

java - Android 检查字符数组中的数字

c# - 获取位图的某个正方形区域

java - 使用mappedby属性时出现Hibernate异常

java - 当你增加一个整数超过它的最大值时会发生什么?

java - 如何从另一个 JInternalFrame 调用 JInternalFrame?

python - Python 3.3 中函数内部的 For 循环问题