Go 程序:两个矩阵相加

在这个 Go 矩阵相加程序中,我们使用了两个嵌套的 for 循环。第一个 for 循环将两个矩阵相加,并将结果赋给相加矩阵。第二个嵌套 for 循环(for i = 0; i < rows; i++ { for j = 0; j < columns; j++)用于打印相加矩阵的元素。

package main

import "fmt"

func main() {
    var rows, columns, i, j int

    var addmat1 [10][10]int
    var addmat2 [10][10]int
    var additionmat [10][10]int

    fmt.Print("Enter the Addition Matrix Rows and Columns = ")
    fmt.Scan(&rows, &columns)

    fmt.Print("Enter the First Matrix Items to Add = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&addmat1[i][j])
        }
    }

    fmt.Print("Enter the Second Matrix Items to Add = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&addmat2[i][j])
        }
    }

    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            additionmat[i][j] = addmat1[i][j] + addmat2[i][j]
        }
    }
    fmt.Println("The Sum of Two Matrices = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Print(additionmat[i][j], "\t")
        }
        fmt.Println()
    }
}
Enter the Addition Matrix Rows and Columns = 2 2
Enter the First Matrix Items to Add = 
10 20
30 40
Enter the Second Matrix Items to Add = 
3 9
14 22
The Sum of Two Matrices = 
13      29
44      62

Golang 矩阵相加程序示例

在这个示例中,我们使用了嵌套的 for 循环范围来为 addmat1 和 addmat2 赋值。接下来,我们使用了另一个嵌套的 for 循环范围来执行矩阵加法并打印结果。

package main

import "fmt"

func main() {

    var addmat1 [2][3]int
    var addmat2 [2][3]int
    var additionmat [2][3]int

    fmt.Print("Enter the First Matrix Items to Add = ")
    for k, r := range addmat1 {
        for l := range r {
            fmt.Scan(&addmat1[k][l])
        }
    }

    fmt.Print("Enter the Second Matrix Items to Add = ")
    for k, r := range addmat2 {
        for l := range r {
            fmt.Scan(&addmat2[k][l])
        }
    }

    fmt.Println("*** The Sum of Two Matrices ****")
    for i, row := range additionmat {
        for j := range row {
            additionmat[i][j] = addmat1[i][j] + addmat2[i][j]
            fmt.Print(additionmat[i][j], "\t")
        }
        fmt.Println()
    }
}
Golang Program to Add Two Matrices