AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
# Kotlin 程序:使用多维数组相加两个矩阵 > 原文: [https://www.programiz.com/kotlin-programming/examples/add-matrix](https://www.programiz.com/kotlin-programming/examples/add-matrix) #### 在此程序中,您将学习在 Kotlin 中使用多维数组相加两个矩阵。 ## 示例:相加两个矩阵的程序 ```kt fun main(args: Array<String>) { val rows = 2 val columns = 3 val firstMatrix = arrayOf(intArrayOf(2, 3, 4), intArrayOf(5, 2, 3)) val secondMatrix = arrayOf(intArrayOf(-4, 5, 3), intArrayOf(5, 6, 3)) // Adding Two matrices val sum = Array(rows) { IntArray(columns) } for (i in 0..rows - 1) { for (j in 0..columns - 1) { sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j] } } // Displaying the result println("Sum of two matrices is: ") for (row in sum) { for (column in row) { print("$column ") } println() } } ``` 运行该程序时,输出为: ```kt Sum of two matrices is: -2 8 7 10 8 6 ``` 在上面的程序中,两个矩阵存储在 2d 数组中,即`firstMatrix`和`secondMatrix`。 我们还定义了行数和列数,并将它们分别存储在变量`rows`和`columns`中。 然后,我们初始化给定行和列的新数组,称为`sum`。 该矩阵数组存储给定矩阵的加法。 我们遍历两个数组的每个索引以添加和存储结果。 最后,我们使用`for`(`foreach`变量)循环遍历`sum`数组中的每个元素以打印元素。 以下是等效的 Java 代码:[使用数组将两个矩阵相加的 Java 程序](/java-programming/examples/add-matrix "Java program to add two matrices using arrays")