【问题标题】:How do I sum a column if the rows and columns are not equal?如果行和列不相等,如何对列求和?
【发布时间】:2020-03-08 20:57:12
【问题描述】:

所以我已经在 2d 数组中进行了其他一些求和列,但它们都具有相同的长度,而我的没有。我已经对行求和(非常简单),但是,当我尝试对列求和时,它会停止,因为第一行中没有数字。我怎样才能让它继续?我已经包括了输出是什么。

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



 public class Main
   {
      public static void main(String args[])
   { 
      int[][] data = { {3, 2, 5},
                     {1, 4, 4, 8, 13},
                     {9, 1, 0, 2},
                     {0, 2, 6, 3, -1, -8} };

       // declare the sum
       int sum;
       int sum2 = 0;

       // compute the sums for each row
       for ( int row=0; row < data.length; row++)
       {
       // initialize the sum, i did it to zero
       sum = 0;


       // compute the sum for this row
       for ( int col=0; col < data[row].length; col++) 
       {
           sum+=data[row][col];
       }

       // write the sum for this row
       System.out.println("The sum of this row is: " + sum);
   }

       for(int i = 0; i < data[0].length; i++)
        {  
          sum2= 0;  
          for(int j = 0; j < data.length; j++)
          {  
            sum2 = sum2 + data[j][i];  
          }   
          System.out.println("Sum of " + (i+1) +" column: " + sum2);  
        }
   }
}





/*Sample Output:
The sum of this row is: 10
The sum of this row is: 30
The sum of this row is: 12
The sum of this row is: 2
Sum of 1 column: 13
Sum of 2 column: 9
Sum of 3 column: 15
*/

谢谢大家!

【问题讨论】:

    标签: arrays loops multidimensional-array


    【解决方案1】:

    试试这个。诀窍是用零作为占位符填充空列:

    int[][] data = { {3, 2, 5},
                     {1, 4, 4, 8, 13},
                     {9, 1, 0, 2},
                     {0, 2, 6, 3, -1, -8} };
    
    int length = 0;
    for (int r = 0; r < data.length; r++) {
        int currLength = data[r].length;
        if(currLength>length) length = currLength;
    }
    // create array for column sums
    int[] sums = new int[length];
    // fill array with zeros
    Arrays.fill(sums, 0);
    // sum up
    for (int currentRow = 0; currentRow < data.length; currentRow++) {
       for (int col = 0; col < data[currentRow].length; col++) {
           sums[col] += data[currentRow][col];
       } 
    }   
    // print sums
    for (int i = 0; i < sums.length; i++) {
        System.out.println("Sum of column " + (i+1) + ": " + sums[i]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 2018-07-22
      • 2020-07-26
      • 2016-10-15
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多