在这个Go程序中,我们使用嵌套的for循环来迭代和打印矩阵项。
package main
import "fmt"
func main() {
var rows, columns, i, j int
var printmat [10][10]int
fmt.Print("Enter the Matrix Rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Print("Enter the Matrix Items = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&printmat[i][j])
}
}
fmt.Println("**** The List of Matrix Items ****")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Printf("The Matrix Item at [%d][%d] Index Position = %d\n", i, j, printmat[i][j])
}
}
}
Enter the Matrix Rows and Columns = 2 2
Enter the Matrix Items =
10 20
9 33
**** The List of Matrix Items ****
The Matrix Item at [0][0] Index Position = 10
The Matrix Item at [0][1] Index Position = 20
The Matrix Item at [1][0] Index Position = 9
The Matrix Item at [1][1] Index Position = 33
Golang程序打印矩阵项
在这个Golang示例中,我们使用矩阵的长度(for i = 0; i < len(printmat); i++)作为for循环条件。
package main
import "fmt"
func main() {
var i, j int
var printmat [2][2]int
fmt.Print("Enter the Matrix Items = ")
for i = 0; i < 2; i++ {
for j = 0; j < 2; j++ {
fmt.Scan(&printmat[i][j])
}
}
fmt.Println("**** The List of Matrix Items ****")
for i = 0; i < len(printmat); i++ {
for j = 0; j < len(printmat[i]); j++ {
fmt.Printf("The Matrix Item at [%d][%d] Index Position = %d\n", i, j, printmat[i][j])
}
}
}
Enter the Matrix Items =
99 88
77 55
**** The List of Matrix Items ****
The Matrix Item at [0][0] Index Position = 99
The Matrix Item at [0][1] Index Position = 88
The Matrix Item at [1][0] Index Position = 77
The Matrix Item at [1][1] Index Position = 55
在这个Golang 示例中,我们使用嵌套的for循环范围为printmat矩阵赋值。接下来,我们使用另一个(for i, row := range printmat { for j, val := range row)来打印这些矩阵项。
package main
import "fmt"
func main() {
var printmat [3][3]int
fmt.Print("Enter the Matrix Items = ")
for k, r := range printmat {
for l := range r {
fmt.Scan(&printmat[k][l])
}
}
fmt.Println("**** The List of Matrix Items ****")
for i, row := range printmat {
for j, val := range row {
fmt.Printf("The Matrix Item at [%d][%d] Index Position = %d\n", i, j, val)
}
}
}
