Go 程序计算矩阵下三角和

编写一个 Go 程序来计算矩阵下三角元素的总和。在此矩阵下三角和示例中,我们使用嵌套的 for 循环来迭代矩阵的行和列元素。在循环中,if 语句 (if i > j) 检查行值是否大于列值。如果为 True,则将该元素值添加到矩阵下三角和中。

package main

import "fmt"

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

    var ltriSumMat [10][10]int

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

    fmt.Println("Enter Matrix Items to find Lower Triangle Sum = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&ltriSumMat[i][j])
        }
    }
    ltriSum := 0
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            if i > j {
                ltriSum = ltriSum + ltriSumMat[i][j]
            }
        }
    }
    fmt.Println("The Sum of Lower Triangle Matrix Elements  = ", ltriSum)
}
Enter the Matrix rows and Columns = 3 3
Enter Matrix Items to find Lower Triangle Sum = 
10 20 30
40 50 60
70 80 90
The Sum of Lower Triangle Matrix Elements  =  190

使用 For 循环范围计算下三角矩阵元素之和的 Golang 程序。

package main

import "fmt"

func main() {

    var ltriSumMat [3][3]int

    fmt.Println("Enter Matrix Items to find Lower Triangle Sum = ")
    for i, rows := range ltriSumMat {
        for j := range rows {
            fmt.Scan(&ltriSumMat[i][j])
        }
    }
    ltriSum := 0
    for i, rows := range ltriSumMat {
        for j := range rows {
            if i > j {
                ltriSum = ltriSum + ltriSumMat[i][j]
            }
        }
    }
    fmt.Println("The Sum of Lower Triangle Matrix Elements  = ", ltriSum)
}
Golang Program to Find Sum of Matrix Lower Triangle