计算矩阵中每一列的总和将为每一列返回相同的结果 [英] Computing the sum of each column in a matrix returns the same result for every column

查看:126
本文介绍了计算矩阵中每一列的总和将为每一列返回相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该将每一列的所有元素相加并给出每个元素的总和.当我运行它时,它只为每列给出相同的答案.我想念什么吗?

This is supposed to add up all elements of each column and give the sum for each. When I run it, it just gives the same answer for each column. Am I missing something?

    import java.util.Scanner;

public class SumColumnElements {
  public static void main(String[] args) {
    double[][] matrix = new double [3][4];

    Scanner input = new Scanner(System.in);
    System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns:");
    for (int row = 0;row < matrix.length; row++) {
      for (int column = 0; column < matrix[row].length; column++) {
        matrix[row][column] = input.nextDouble();
      }
    }
    sumColumn(matrix,0);
  }
  public static double sumColumn(double[][] m, int columnIndex) {
        double total = 0;
        for (int column = 0; column <= columnIndex; column++) {
          total = 0;
          for (int row = 0; row < m.length; row++) {
            total += m[row][column];
           //System.out.println("The sum for column "+column+" until row "+row+" is " + total);
          }              
         System.out.println("The sum for column "+ column + " is " + total);            

        }
        return total;
}
}

推荐答案

在大多数情况下,该程序对我而言都是正确的.以下是一些小调整:

The program looks correct to me for most parts. Here are some minor tweaks:

import java.util.Scanner;

public class SumColumnElements {

  public static final int ROW = 3;
  public static final int COLMN = 4;

  public static void main(String[] args) {
    double[][] matrix = new double [ROW][COLMN];

    Scanner input = new Scanner(System.in);
    System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns:");
    for (int row = 0;row < matrix.length; row++) {
      for (int column = 0; column < matrix[row].length; column++) {
        matrix[row][column] = input.nextDouble();
      }
    }
    sumColumn(matrix, COLMN);
  }
  public static double sumColumn(double[][] m, int columnIndex) {
    System.out.println("columnIndex: " + columnIndex);
    double total = 0;
    for (int column = 0; column < columnIndex; column++) {
      total = 0;
      for (int row = 0; row < m.length; row++) {
        total += m[row][column];
      }
      System.out.println("The sum for column "+ column + " is " + total);
    }
    return total;
  }
}

对于特定输入:

1  2  3  4

5  6  7  8

9 10 11 12

输出将是:

The sum for column 0 is 15.0
The sum for column 1 is 18.0
The sum for column 2 is 21.0
The sum for column 3 is 24.0

这篇关于计算矩阵中每一列的总和将为每一列返回相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆