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 数组中的每个元素来打印这些元素。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战