使用多维数组添加两个矩阵的 Java 程序

在本程序中,您将学习在 Java 中使用多维数组将两个矩阵相加。

要理解此示例,您应该具备以下 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} };

        // Adding Two matrices
        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];
            }
        }

        // Displaying the result
        System.out.println("Sum of two matrices is: ");
        for(int[] row : sum) {
            for (int column : row) {
                System.out.print(column + "    ");
            }
            System.out.println();
        }
    }
}

输出

Sum of two matrices is:
-2    8    7    
10    8    6   

在上面的程序中,两个矩阵存储在二维数组中,即 firstMatrixsecondMatrix. 我们还定义了行数和列数并将它们存储在变量中 rowscolumns 分别。

然后,我们初始化一个给定行和列的新数组,称为 sum. 此矩阵数组存储给定矩阵的相加。

我们遍历两个数组的每个索引以添加和存储结果。

最后,我们使用 for-each 循环遍历 sum 数组中的每个元素来打印元素。