Go 语言检查单位矩阵的程序

编写一个 Go 程序来检查给定的矩阵是否是单位矩阵。任何方阵,如果其主对角线上的元素都是 1,而所有其他元素都是 0,则为单位矩阵。在嵌套的 for 循环中,我们使用 if 语句 (if identMat[i][j] != 1 && identMat[j][i] != 0) 来检查对角线是否不为零,其他元素是否为一。

如果任何条件为真,则将 flag 值赋为零,break 语句将终止循环。最后一个 If else 语句 (if flag == 1) 根据 flag 值打印结果。

package main

import "fmt"

func main() {
    var num, i, j int

    var identMat [10][10]int

    fmt.Print("Enter the Matrix Size = ")
    fmt.Scan(&num)

    fmt.Print("Enter the Matrix Items = ")
    for i = 0; i < num; i++ {
        for j = 0; j < num; j++ {
            fmt.Scan(&identMat[i][j])
        }
    }
    flag := 1
    for i = 0; i < num; i++ {
        for j = 0; j < num; j++ {
            if identMat[i][j] != 1 && identMat[j][i] != 0 {
                flag = 0
                break
            }
        }
    }
    if flag == 1 {
        fmt.Println("It is an Idenetity Matrix")
    } else {
        fmt.Println("It is Not an Idenetity Matrix")
    }
}
Go Program to Check Identity Matrix

Golang 程序检查矩阵是否为单位矩阵

在此 示例 中,我们使用 Else If 来查找单位矩阵。

package main

import "fmt"

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

    var identMat [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(&identMat[i][j])
        }
    }
    flag := 1
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            if (i == j) && (identMat[i][j] != 1) {
                flag = 0
            } else if (i != j) && (identMat[i][j] != 0) {
                flag = 0
            }
        }
    }
    if flag == 1 {
        fmt.Println("It is an Idenetity Matrix")
    } else {
        fmt.Println("It is Not an Idenetity Matrix")
    }
}
SureshMac:GoExamples suresh$ go run matIdentity2.go
Enter the Matrix Rows and Columns = 2 2
Enter the Matrix Items =  
1 0
0 1
It is an Idenetity Matrix
SureshMac:GoExamples suresh$ go run matIdentity2.go
Enter the Matrix Rows and Columns = 3 3
Enter the Matrix Items = 
1 0 0
0 0 1
0 1 0
It is Not an Idenetity Matrix