我用 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)
}
}
}
Playground :https://play.golang.org/p/Awuw2Th1g2V
输出:
9
我教科书中的解决方案不同,我理解那里的逻辑。
最佳答案
要找到列表中的最小数字,您需要遍历列表并存储您当前找到的最小数字。将这个“迄今为止最小”的数字与列表中的其他数字进行比较,如果您发现一个较小的数字,请用它替换您的最小数字。在迭代结束时,您将知道列表中的最小数字。
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)
关于arrays - 查找列表中的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182202/