程序应将2个矩阵4x1和1x4相乘,并将结果输出到控制台(矩阵4X4)。但是什么也没显示。有什么问题吗?
public class Matrix {
public static void main(String[] args) {
int[][] matrixA = new int [4][1];
int[][] matrixB = new int [1][4];
int[][] matrixC = new int [4][4];
matrixA[0][0] = 1;
matrixA[1][0] = 2;
matrixA[2][0] = 3;
matrixA[3][0] = 4;
matrixB[0][0] = 4;
matrixB[0][1] = 3;
matrixB[0][2] = 2;
matrixB[0][3] = 1;
for (int i = 0; i < 4; i++) { // A rows
for (int j = 0; j < 4; j++) { // B columns
for (int k = 0; k < 1; k++) { // A columns
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
System.out.print(matrixC[i][j]+ " ");
}
}
}
int j = 0;
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 1; k++)
System.out.print(matrixC[i][j]+ " ");
System.out.println();
}
} //end main
} //结束课程
答案 0 :(得分:1)
您在第二组j
循环之前引入了变量for
。另外,即使它们是可选的,我也强烈建议始终包含大括号。还有k < 4
。喜欢,
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 4; k++) {
System.out.print(matrixC[i][k] + " "); // not [i][j]
}
System.out.println();
}
或就像
一样使用Arrays.deepToString(Object[])
System.out.println(Arrays.deepToString(matrixC));
答案 1 :(得分:0)
我解决了这个问题!现在显示4x4。感谢您的帮助!
public class Matrix {
public static void main(String[] args) {
int[][] matrixA = new int [4][1];
int[][] matrixB = new int [1][4];
int[][] matrixC = new int [4][4];
matrixA[0][0] = 1;
matrixA[1][0] = 2;
matrixA[2][0] = 3;
matrixA[3][0] = 4;
matrixB[0][0] = 4;
matrixB[0][1] = 3;
matrixB[0][2] = 2;
matrixB[0][3] = 1;
for (int i = 0; i < 4; i++) { // A rows
for (int j = 0; j < 4; j++) { // B columns
for (int k = 0; k < 1; k++) { // A columns
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
System.out.print(matrixC[i][j]+ " ");
//System.out.println();
}
}
System.out.println();
}
} //end main
} //end class
答案 2 :(得分:0)
希望这会有所帮助:
public class Matrix {
public static void main(String[] args) {
int[][] matrixA = {{1}, {2}, {3}, {4}};
int[][] matrixB = {{4, 3, 2, 1}};
int[][] matrixC = new int[4][4];
for (int i = 0; i < 4; i++) { // A rows
for (int j = 0; j < 4; j++) { // B columns
for (int k = 0; k < 1; k++) { // A columns
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
System.out.print(matrixC[i][j] + " ");
}
}
System.out.println();
}
}
}
输出:
4 3 2 1
8 6 4 2
12 9 6 3
16 12 8 4