Question: Can anyone help me with this problem? Enter a number n and then a floating-point array of n x n. Calculate the sum of the

Can anyone help me with this problem?

Enter a number n and then a floating-point array of n x n. Calculate the sum of the reverse diagonal numbers in the array, keeping two decimal places for the result.

Below is my code:

import java.util.*;

public class Main {

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

double [][] arr = new double[n][n];

double sum = 0.00;

for(int i = 0; i < n ;i++)

{

for(int j = 0; j < n ; j++)

{

arr[i][j] = sc.nextDouble();

// System.out.println(arr[i][j]);

}

}

for(int x = 0; x < n; x++)

{

for(int y=n-1;y>=0;y--)

{

sum += arr[x][y];

break;

}

}

String res = String.format("%.2f",sum);

System.out.println(res);

}

}

And here is the input:

4 1.1 2.2 3.3 4.4 0.1 0.2 0.3 0.4 1.0 2.0 3.0 4.0 9.1 8.2 7.3 6.4

the expected output should be 15.80, but my code returns 15.20

Can anyone tell me where is 0.20 comes from and how to fix that, thanks!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!