這應該是將每列的所有元素相加並給出每列的總和。當我運行它時,它對每列都給出相同的答案。我錯過了什麼嗎?計算矩陣中每列的總和會爲每列返回相同的結果
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;
}
}
任何特定的語言? – 2014-12-06 03:59:01
我正在使用DrJava。 – 2014-12-06 03:59:58
您將四個println命令放在一起,因爲'total'在這些行之間沒有變化,所以每個輸出都使用相同的值。應該只有一個println命令,並且列(0,1,2,3)的索引不應該被編入,而是從'column'變量中獲取。 – 2014-12-06 04:06:18