用java编写写出一个方法,计算两个矩阵的乘积。
时间: 2024-06-12 17:09:21 浏览: 94
计算两个矩形的乘积
可以使用以下Java代码来计算两个矩阵的乘积:
```java
public class MatrixMultiplication {
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int rowsA = matrixA.length;
int colsA = matrixA[0].length;
int colsB = matrixB[0].length;
int[][] result = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
public static void main(String[] args) {
int[][] matrixA = {{1, 2, 3}, {4, 5, 6}};
int[][] matrixB = {{7, 8}, {9, 10}, {11, 12}};
int[][] result = multiply(matrixA, matrixB);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
```
阅读全文