这是我正在研究的问题: 编写一个读取3 x 4矩阵并显示每个矩阵之和的程序 列和每一行分别。
这是示例运行: 逐行输入3 x 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
变量。我一直在玩它,并且可能已经改变了几个小时,而我似乎无法正确解决这个问题,有人可以帮我解决我做错的事情吗?还不知道我是否在正确地进行列求和?
答案 0 :(得分:2)
在您的matrix
中,它是代码段double[][] matrix = new double[3][4];
中的3×4矩阵。第一个索引是行索引,第二个索引是列索引。
请注意,您的double[][]
矩阵是数组数组。即,matrix
是由三个长度为4的数组组成的数组,按照惯例,每个子数组都可以看作是排列成一行的对象的数组。这称为行主要订单。
例如,在数组中
0 1 2 4
0 1 3 9
0 1 5 15
它实际上存储为
matrix[0]: [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3]
和[0 1 2 4]
matrix[1]: [matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3]
和[0 1 3 9]
matrix[2]: [matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3]
和[0 1 5 25]
这是一种更简单的算法,该算法使用循环来查找每个行和列值的值总和,但需要两次通过:
/* After the prompt code segment and sumOfCol in the main method */
// Row (major index)
for (int row = 0; row < matrix.length; row++) {
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
rowSum += matrix[row][col];
}
System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
}
// Column (minor index)
// Assuming the length of each row is the same
for (int col = 0; col < matrix[0].length; col++) {
int colSum = 0;
for (int row = 0; row < matrix.length; row++) {
colSum += matrix[row][col];
}
System.out.println("Sum of the elements at col " + col + " is: " + colSum);
}
输出为
Enter a 3 by 4 matrix row by row:
0 1 2 4
0 1 3 9
0 1 5 15
Sum of the elements at row 0 is: 7
Sum of the elements at row 1 is: 13
Sum of the elements at row 2 is: 21
Sum of the elements at col 0 is: 0
Sum of the elements at col 1 is: 3
Sum of the elements at col 2 is: 10
Sum of the elements at col 3 is: 28
答案 1 :(得分:0)
计算行数的变量在打印行总和时称为i
。
对于列总和,您需要另一个循环来逐个打印它们。