java二维数组矩阵相加
时间: 2023-11-20 15:55:25 浏览: 213
以下是Java中实现二维数组矩阵相加的代码:
```java
public class MatrixAddition {
public static double[][] addMatrix(double[][] a, double[][] b) {
int rows = a.length;
int columns = a[0].length;
double[][] result = new double[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public static void printMatrix(double[][] matrix) {
for (double[] row : matrix) {
for (double element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
double[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
double[][] b = {{0, 2, 4}, {1.1, 4.3, 5.2}, {1, 4.5, 2.2}};
double[][] result = addMatrix(a, b);
printMatrix(result);
}
}
```
输出结果为:
```
1.0 4.0 7.0
5.1 9.3 11.2
8.0 12.5 11.2
```
阅读全文