在此 Go 矩阵乘法程序中,我们使用了两个 for 循环。第一个 for 循环执行矩阵乘法并将值赋给乘法矩阵。第二个 for 循环打印该矩阵中的项。
package main
import "fmt"
func main() {
var rows, columns, i, j int
var multimat1 [10][10]int
var multimat2 [10][10]int
var multiplicationnmat [10][10]int
fmt.Print("Enter the Multiplication Matrix Rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Print("Enter the First Matrix Items to Multiplication = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&multimat1[i][j])
}
}
fmt.Print("Enter the Second Matrix Items to Multiplication = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&multimat2[i][j])
}
}
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
multiplicationnmat[i][j] = multimat1[i][j] * multimat2[i][j]
}
}
fmt.Println("The Go Result of Matrix Multiplication = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Print(multiplicationnmat[i][j], "\t")
}
fmt.Println()
}
}
Enter the Multiplication Matrix Rows and Columns = 2 2
Enter the First Matrix Items to Multiplication =
10 20
30 40
Enter the Second Matrix Items to Multiplication =
3 4
5 6
The Go Result of Matrix Multiplication =
30 80
150 240
Go 程序示例:两个矩阵相乘
在此 示例中,我们使用 for 循环 range 将值赋给 multimat1 和 multimat2。接下来,我们使用另一个 for 循环执行矩阵乘法并打印结果。您也可以使用另一个 for 循环来打印矩阵项。
package main
import "fmt"
func main() {
var multimat1 [2][3]int
var multimat2 [2][3]int
var multiplicationnmat [2][3]int
fmt.Print("Enter the First Matrix Items to Multiplication = ")
for k, r := range multimat1 {
for l := range r {
fmt.Scan(&multimat1[k][l])
}
}
fmt.Print("Enter the Second Matrix Items to Multiplication = ")
for m, rr := range multimat2 {
for n := range rr {
fmt.Scan(&multimat2[m][n])
}
}
fmt.Println("The Go Result of Matrix Multiplication = ")
for i, row := range multiplicationnmat {
for j := range row {
multiplicationnmat[i][j] = multimat1[i][j] * multimat2[i][j]
fmt.Print(multiplicationnmat[i][j], "\t")
}
fmt.Println()
}
}
