【问题标题】:matrix column sum java矩阵列总和java
【发布时间】:2017-12-23 12:51:08
【问题描述】:

我最近在 Java 中工作。我还在为 Java 苦苦挣扎。任务是分别对列和行求和,示例如下所示。 我设法得到了列的总和,但我总是在我想要的输出中重复第一行,我怎样才能删除那个错误。并且只有所需的列总和。

它是如何分别对行总和起作用的?

非常感谢您提前提供的帮助

代码如下:

public class MatrixColumnSums {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    double [][] a = new double [2][3]; 
    a[0][0] = 1; 
    a[0][1] = 2; 
    a[0][2] = 3; 
    a[1][0] = 4; 
    a[1][1] = 5; 
    a[1][2] = 6;

    System.out.println( "A");
    for (int i = 0; i < a.length; i++) {
        String str = "";
        for (int j = 0; j < a[i].length; j++) {
            str += a[i][j] + "\t"; 
        }
        System.out.println(str);
        }
    // column sums 
    // creating another matrix to store the sum of columns matrices
                double c[] = new double  [a[0].length]; 

                // Adding and printing addition of 2 matrices
                System.out.println("C");

                for (int i = 0; i < a.length; i++) {
                    for (int j = 0; j < a[0].length; j++)
                    {   
                        c[j] += a[i][j]; 

                        System.out.print(c[j] + "\t");

                    }
                    System.out.println(); 
               }

             }
          } 

输出如下所示:

一个

1.0 2.0 3.0

4.0 5.0 6.0

C

1.0 2.0 3.0(

5.0 7.0 9.0(我只想把它作为我的输出)

【问题讨论】:

    标签: java add


    【解决方案1】:

    **矩阵列总和**

    doOneColumnSum 方法对一列求和。

     private static double doOneColumnSum(double[][] arr, int col){
    
        double total = 0;
        for (int row = 0; row < arr.length; row += 1){
          total += arr[row][col];
        }
        return total;
      }
    

    doColumnSums 方法使用 doOneColumnSum 方法对所有列求和

    public static double[] doColumnSums(double[][] arr)
      {
        int numColumns = arr[0].length;
        double[] result = new double[numColumns];
        for (int col = 0; col < numColumns; col += 1)
        {
          result[col] = findOneColumnSum(arr, col);
        }
        return result;
      }
    

    【讨论】:

      【解决方案2】:

      c矩阵求和时不打印,只在最后打印一次:

      // sum the columns first
      for (int i=0; i < a.length; i++) {
          for (int j=0; j < a[0].length; j++) {
              c[j] += a[i][j];
          }
      }
      
      // then iterate c[] once at the end and print it
      for (int j=0; j < a[0].length; j++) {
          System.out.print(c[j] + "\t");
      }
      

      请注意,我们可以将 if 逻辑添加到您的原始嵌套循环中,以便仅在求和完成后打印 c,但从关注点分离的角度来看,我上面写的内容似乎更有吸引力。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多