问题描述
任何人都可以在这里告诉我为什么使用Go示例吗?
Can anyone please tell me why the Go example here:
https://tour.golang.org/basics/1
是否总是为rand.Intn(10)返回相同的值?
always returns the same value for rand.Intn(10)?
推荐答案
2个原因:
-
您必须初始化由
Source
a href ="https://golang.org/pkg/math/rand/#Intn" rel ="noreferrer">rand.Intn()
和rand
包的其他功能,使用rand.Seed()
.例如:
You have to initalize the global
Source
used byrand.Intn()
and other functions of therand
package usingrand.Seed()
. For example:
rand.Seed(time.Now().UnixNano())
请参阅 Go Rand软件包存在的困难.
引用 rand
的软件包文档:
See possible duplicate of Difficulty with Go Rand package.
Quoting from package doc of rand
:
The Tour runs examples on the Go Playground which caches its output.
See details at Why does count++ (instead of count = count + 1) change the way the map is returned in Golang.
这篇关于Go rand.Intn相同的数字/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!