我用 Go 编写了一个程序,可以查找列表中的最小数字并且它可以工作。但是,我不太明白其中的逻辑。您能解释一下它是如何工作的吗?
package main
import "fmt"
func main() {
x := []int{
48, 96, 86, 68,
57, 82, 63, 70,
37, 34, 83, 27,
19, 97, 9, 17,
}
for i, num := range x {
if num < i {
fmt.Println(num)
}
}
}
Run Code Online (Sandbox Code Playgroud)
游乐场:https://play.golang.org/p/Awuw2Th1g2V
输出:
9
Run Code Online (Sandbox Code Playgroud)
我教科书上的解决方案是不同的,我理解其中的逻辑。
要找到列表中的最小数字,您需要迭代列表并存储当前找到的最小数字。将这个“迄今为止最小”的数字与列表中的每个其他数字进行比较,如果找到较小的数字,则用它替换最小的数字。在迭代结束时,您将知道列表中的最小数字。
smallest := x[0] // set the smallest number to the first element of the list
for _, num := range x[1:] { // iterate over the rest of the list
if num < smallest { // if num is smaller than the current smallest number
smallest = num // set smallest to num
}
}
fmt.Println(smallest)
Run Code Online (Sandbox Code Playgroud)