sum of columns in a 2 dimensional array

后端 未结 5 1036
太阳男子
太阳男子 2020-12-18 10:54
static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};

public double[] columnSum(         


        
5条回答
  •  没有蜡笔的小新
    2020-12-18 11:40

    So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.

    You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.

    for (int i = 0, j = 0; i < initialArray[j].length; i++) {
      for (; j < initialArray.length; j++) {
        System.out.println(i + " " + j);
      }
      j = 0;
    }
    

    And here is your modified program.

    public class Main {
      static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
    
      public double[] columnSum(double[][] array) {
        int index = 0;
        double temp[] = new double[array[index].length];
        for (int i = 0; i < array[0].length; i++) {
          double sum = 0;
          for (int j = 0; j < array.length; j++) {
            sum += array[j][i];
          }
          temp[index] = sum;
          System.out.println("Index is: " + index + " Sum is: " + sum);
          index++;
        }
        return temp;
      }
    
      public static void main(String[] args) {
        new Main().columnSum(initialArray);
      }
    }
    

提交回复
热议问题