2D Array Elements sum incorrect [closed]

I need to find the sum of all the elements in my 2D Array but the elements are doubles and they’re only being added as integers. The output is coming out as 55 when it should come out as 59.6. Any form of help is greatly appreciated. Thanks

class Main{
public static void main(String[] args){
double[][] step4 = {{1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6}, {7.7, 8.8}, {9.9, 10.10}};
        int sum = 0;
        for (int r = 0; r < step4.length; r++){
          for (int c = 0; c < step4[r].length; c++){
            sum += step4[r][c];


Change your sum variable from int to double. Because you are doing addition with doubles and in the end you cast them to int.

Leave a Reply

Your email address will not be published. Required fields are marked *