这是我正在解决的问题:编写一个程序,读取一个 3 x 4 矩阵并分别显示每列和每行的总和。
这是示例运行:逐行输入 3×4 矩阵:
1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0
Sum of the elements at Row 0 is: 10.5
Sum of the elements at Row 0 is: 26.5
Sum of the elements at Row 0 is: 14.5
这是我想出的代码:
package multidimensionalarrays;
public class MultidimensionalArrays {
public static void main(String[] args) {
double sumOfRow = 0;
double[][] matrix = new double[3][4];
java.util.Scanner input = new java.util.Scanner(System.in); //Scanner
System.out.println("Enter a 3 by 4 matrix row by row: ");
//Prompt user to enter matrix numbers
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
matrix[row][col] = input.nextDouble();
}
}
double[] sumOfCol =new double[matrix[0].length];
for (int i = 0; i < matrix.length; i++) { //row
for (int j = 0; j < matrix[i].length; j++) { //column
sumOfRow += matrix[i][j];
sumOfCol[j] += matrix[i][j];
}
System.out.println("Sum of the elements at row " + row + " is: " + sumOfRow);
}
System.out.println("Sum of the elements at column " + col + " is: " + sumOfCol);
}
}
我的问题是,当最后打印列和行的总和时,它无法识别row或col变量。我一直在玩它,现在可能已经改变了几个小时,但我似乎无法做到这一点,有人可以帮助我解决我做错了什么吗?另外我不知道我是否正确地进行了列求和?
DIEA
相关分类