Go 程序查找矩阵上三角之和

编写一个 Go 程序来查找矩阵上三角元素的总和。在这个 Go 矩阵上三角之和的例子中,嵌套的 for 循环会遍历矩阵的行和列元素。在循环内部,if 语句(if j > i)会检查列值是否大于行。如果为真,则将该元素值添加到矩阵上三角总和中。

package main

import "fmt"

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

    var upTriSumMat [10][10]int

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

    fmt.Println("Enter Matrix Items to find Upper Triangle Sum = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&upTriSumMat[i][j])
        }
    }
    upTriSum := 0
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            if j > i {
                upTriSum = upTriSum + upTriSumMat[i][j]
            }
        }
    }
    fmt.Println("The Sum of Upper Triangle Matrix Elements  = ", upTriSum)
}
Enter the Matrix rows and Columns = 3 3
Enter Matrix Items to find Upper Triangle Sum = 
10 20 30
40 50 90
10 11 44
The Sum of Upper Triangle Matrix Elements  =  140

Golang 程序使用 For 循环范围查找矩阵上三角元素之和。

package main

import "fmt"

func main() {

    var upTriSumMat [3][3]int

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