Go 语言查找最小数组项程序

编写一个 Go 程序,使用 For 循环查找最小数组项或数字。首先,我们将第一个数组项赋值给 smallest 变量 (smallest = smArr[0])。在 For 循环中 (for i = 0; i < smsize; i++),if 条件 (if smallest > smArr[i]) 检查当前数组项是否大于 smallest。如果为 True,则将该值赋给 smallest 变量,并将索引值赋给 position 变量。

package main

import "fmt"

func main() {
    var smsize, i, position int

    fmt.Print("Enter the Array Size to find the Smallest = ")
    fmt.Scan(&smsize)

    smArr := make([]int, smsize)

    fmt.Print("Enter the Smallest Array Items  = ")
    for i = 0; i < smsize; i++ {
        fmt.Scan(&smArr[i])
    }
    smallest := smArr[0]

    for i = 0; i < smsize; i++ {
        if smallest > smArr[i] {
            smallest = smArr[i]
            position = i
        }
    }
    fmt.Println("\nThe Smallest Number in this smArr    = ", smallest)
    fmt.Println("The Index Position of Smallest Number = ", position)
}
Enter the Array Size to find the Smallest = 5
Enter the Smallest Array Items  = 10 8 22 4 19

The Smallest Number in this smArr    =  4
The Index Position of Smallest Number =  3

Go 语言使用 For Loop Range 查找最小数组数程序

package main

import "fmt"

func main() {
    var smsize, i, position int

    fmt.Print("Enter the Array Size to find the Smallest = ")
    fmt.Scan(&smsize)

    smArr := make([]int, smsize)

    fmt.Print("Enter the Smallest Array Items  = ")
    for i = 0; i < smsize; i++ {
        fmt.Scan(&smArr[i])
    }
    smallest := smArr[0]

    for i, sm := range smArr {
        if smallest > sm {
            smallest = sm
            position = i
        }
    }
    fmt.Println("\nThe Smallest Number in this smArr    = ", smallest)
    fmt.Println("The Index Position of Smallest Number = ", position)
}
Go Program to Find Smallest Array Item

在此 Golang 程序中,我们创建了一个函数 (smallestNum(smArr []int) (int, int)),该函数将返回数组中的最小项或数字及其索引位置。

package main

import "fmt"

var smallest, position int

func smallestNum(smArr []int) (int, int) {
    smallest = smArr[0]
    for i, sm := range smArr {
        if smallest > sm {
            smallest = sm
            position = i
        }
    }
    return smallest, position
}

func main() {
    var smsize, i int

    fmt.Print("Enter the Array Size to find the Smallest = ")
    fmt.Scan(&smsize)

    smArr := make([]int, smsize)

    fmt.Print("Enter the Smallest Array Items  = ")
    for i = 0; i < smsize; i++ {
        fmt.Scan(&smArr[i])
    }
    smallest, position := smallestNum(smArr)

    fmt.Println("\nThe Smallest Number in this smArr     = ", smallest)
    fmt.Println("The Index Position of Smallest Number = ", position)
}
Enter the Array Size to find the Smallest = 6
Enter the Smallest Array Items  = 9 129 33 1 8 60

The Smallest Number in this smArr     =  1
The Index Position of Smallest Number =  3