编写一个Go程序来转置矩阵,将行转换为列,列转换为行。在这个Go示例中,我们使用了第一个嵌套for循环将行转换为列(transposeMat[j][i] = orgMat[i][j)反之亦然。下一个循环打印转置矩阵中的元素。
package main
import "fmt"
func main() {
var i, j, rows, columns int
var orgMat [10][10]int
var transposeMat [10][10]int
fmt.Print("Enter the Matrix rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Println("Enter Matrix Items to Transpose = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&orgMat[i][j])
}
}
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
transposeMat[j][i] = orgMat[i][j]
}
}
fmt.Println("*** The Transpose Matrix Items are ***")
for i = 0; i < columns; i++ {
for j = 0; j < rows; j++ {
fmt.Print(transposeMat[i][j], " ")
}
fmt.Println()
}
}
Enter the Matrix rows and Columns = 2 3
Enter Matrix Items to Transpose =
1 2 3
4 8 7
*** The Transpose Matrix Items are ***
1 4
2 8
3 7
Golang程序使用For循环范围转置矩阵。
package main
import "fmt"
func main() {
var orgMat [3][3]int
var transposeMat [3][3]int
fmt.Println("Enter Matrix Items to Transpose = ")
for i, rows := range orgMat {
for j := range rows {
fmt.Scan(&orgMat[i][j])
}
}
for i, rows := range orgMat {
for j := range rows {
transposeMat[j][i] = orgMat[i][j]
}
}
fmt.Println("*** The Transpose Matrix Items are ***")
for i, rows := range orgMat {
for j := range rows {
fmt.Print(transposeMat[i][j], " ")
}
fmt.Println()
}
}
