用java定义两个二维数组,分别用于存储两个3*3的矩阵的元素值,求出这两个 矩阵的乘积,并输出计算结果。
时间: 2024-09-09 16:01:22 浏览: 97
java 二维数组矩阵乘法的实现方法
5星 · 资源好评率100%
在Java中,我们可以首先定义两个3x3的二维数组来存储矩阵的元素,然后创建一个方法来计算这两个矩阵的乘积。这里是一个简单的例子:
```java
public class Main {
static int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
static int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
// 计算两个矩阵相乘
public static int[][] multiplyMatrices(int[][] first, int[][] second) {
int rowsFirst = first.length;
int colsFirst = first[0].length;
int rowsSecond = second.length;
int colsSecond = second[0].length;
if (colsFirst != rowsSecond) {
throw new IllegalArgumentException("Matrix dimensions don't allow multiplication");
}
int[][] result = new int[rowsFirst][colsSecond];
for (int i = 0; i < rowsFirst; i++) {
for (int j = 0; j < colsSecond; j++) {
for (int k = 0; k < colsFirst; k++) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
return result;
}
public static void main(String[] args) {
int[][] product = multiplyMatrices(matrix1, matrix2);
// 输出结果矩阵
for (int[] row : product) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
阅读全文