在此程序中,您将学习使用Java中的多维数组将两个矩阵相加。
public class AddMatrices {
public static void main(String[] args) {
int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };
//两个矩阵相加
int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
//显示结果
System.out.println("两个矩阵的和为: ");
for(int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
运行该程序时,输出为:
两个矩阵的和为:
-2 8 7
10 8 6
在上面的程序中,两个矩阵存储在2d数组中,即firstMatrix和secondMatrix。 我们还定义了行数和列数,并将它们分别存储在变量行和列中
然后,我们初始化给定行和列的新数组,称为sum。 该矩阵数组存储给定矩阵的加法。
我们遍历两个数组的每个索引以添加和存储结果。
最后,我们使用for(foreach变量)循环遍历sum数组中的每个元素以打印元素。