对角线差异代码不起作用

时间:2017-10-02 04:01:18

标签: java diagonal

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        int sum1=0, sum2=0;
        Scanner in= new Scanner(System.in);
        int rows = in.nextInt();
        int[][] matrix= new int[rows][rows];
        for(int i=0; i<rows; i++)
        {
            for(int j=0; j<rows; j++)
            {
                matrix[i][j]=in.nextInt();
                if(i==j)
                {
                    sum1=sum1+matrix[i][j];
                }
                else if((i+j)%2==0)
                {
                    sum2=sum2+matrix[i][j];
                }
            }
        }
        System.out.print(Math.abs(sum2-sum1));
    }
}

此代码用于查找对角线差异。但这不能正常工作。有人可以帮我纠正这段代码吗?

3 个答案:

答案 0 :(得分:0)

您可以在评估sum2时修改条件:

else if((i+j)%2==0) //e.g [2,2] would also be included in this sum otherwise 

else if((i+j) == rows-1) 
// the inverse diagonal holds that the sum of its indexes would be equal to the size of the square matrix

答案 1 :(得分:0)

我修改了一下,但主要问题是:

  • 您错误地计算了第二个对角线。
  • 两个else语句之间的if阻止奇数大小的矩阵将中间值添加到第二个对角线。

所以,它应该是这样的:

public static void main( String[] args )
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    try ( Scanner in = new Scanner( System.in ) )
    {
        int sum1 = 0, sum2 = 0;
        System.out.print( "Enter size: " );
        int rows = in.nextInt();
        in.nextLine();
        System.out.println( "Enter matrix:" );
        int[][] matrix = new int[rows][rows];
        for ( int i = 0 ; i < rows ; i++ )
        {
            for ( int j = 0 ; j < rows ; j++ )
            {
                matrix[i][j] = in.nextInt();
                if ( i == j )
                {
                    System.out.printf( "i = j = %d, [i,j] = %d%n", i, matrix[i][j] );
                    sum1 = sum1 + matrix[i][j];
                }
                if ( i + j == rows - 1 )
                {
                    System.out.printf( "i = %d, j = %d, [i,j] = %d%n", i, j, matrix[i][j] );
                    sum2 = sum2 + matrix[i][j];
                }
            }
        }
        System.out.printf( "%nsum1 = %d, sum2 = %d, difference = %d%n", sum1, sum2,
                           Math.abs( sum2 - sum1 ) );
    }
}

答案 2 :(得分:0)

int sum1 = 0, sum2 = 0; //let sum1 and sum2 be your sum of diagonals

    for (int i = 0; i < n; i++)// let n be the size of the matrix
    {
        for (int j = 0; j < n; j++)
        {
            // finding sum of primary diagonal
            if (i == j)
                d1 += arr[i][j];
//finding sum of secondary diagonal
 if (i == n - j - 1)
                d2 += arr[i][j];
        }
    }

    // Absolute difference of the sums
    // across the diagonals
    return abs(d1 - d2);