编写一个 Go 程序来查找矩阵对角线项的总和。在此 Go 示例中,我们使用 for 循环迭代行项,并将矩阵对角线项添加到总和中 (sum = sum + dSumMat[i][I])。
package main
import "fmt"
func main() {
var i, j, rows, columns int
var dSumMat [10][10]int
fmt.Print("Enter the Matrix rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Println("Enter the Matrix Items to find the Diagonal Sum = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&dSumMat[i][j])
}
}
sum := 0
for i = 0; i < rows; i++ {
sum = sum + dSumMat[i][i]
}
fmt.Println("The Sum of Matrix Diagonal Elements = ", sum)
}
Enter the Matrix rows and Columns = 2 2
Enter the Matrix Items to find the Diagonal Sum =
10 20
30 50
The Sum of Matrix Diagonal Elements = 60
Golang 程序使用 For 循环范围查找矩阵中对角线元素的总和。
package main
import "fmt"
func main() {
var dSumMat [3][3]int
fmt.Println("Enter the Matrix Items to find the Diagonal Sum = ")
for i, rows := range dSumMat {
for j := range rows {
fmt.Scan(&dSumMat[i][j])
}
}
sum := 0
for k := range dSumMat {
sum = sum + dSumMat[k][k]
}
fmt.Println("The Sum of Matrix Diagonal Elements = ", sum)
}
