简体   繁体   English

去 rand.Intn 相同的数字/值

[英]Go rand.Intn same number/value

Can anyone please tell me why the Go example here:谁能告诉我为什么这里有 Go 示例:

https://tour.golang.org/basics/1 https://tour.golang.org/basics/1

always returns the same value for rand.Intn(10)?总是为 rand.Intn(10) 返回相同的值?

2 reasons: 2个原因:

  1. You have to initalize the global Source used by rand.Intn() and other functions of the rand package using rand.Seed() .你必须initalize全球Source的使用rand.Intn()和其他功能rand使用包rand.Seed() For example:例如:

     rand.Seed(time.Now().UnixNano())

    See possible duplicate of Difficulty with Go Rand package .查看使用 Go Rand 包Difficulty 的可能重复项。
    Quoting from package doc of rand :引用rand包文档:

    Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run.诸如 Float64 和 Int 之类的顶级函数使用默认的共享源,该在每次程序运行时生成确定性的值序列。 Use the Seed function to initialize the default Source if different behavior is required for each run.如果每次运行需要不同的行为,请使用 Seed 函数来初始化默认 Source。

  2. The Tour runs examples on the Go Playground which caches its output. Tour在缓存其输出的Go Playground上运行示例。
    See details at Why does count++ (instead of count = count + 1) change the way the map is returned in Golang .请参阅为什么 count++(而不是 count = count + 1)会改变 Golang 中返回地图的方式中的详细信息

For the functions in the rand package to work you have to set a 'Seed' value.要使 rand 包中的函数正常工作,您必须设置一个“种子”值。 This has to be a good random value as decided by the user because - as per https://golang.org/pkg/math/rand/#Rand.Seed this is the value golang uses to set the system to a deterministic state first to then generate a number based on that value.这必须是用户决定的一个很好的随机值,因为 - 根据https://golang.org/pkg/math/rand/#Rand.Seed这是 golang 用来首先将系统设置为确定性状态的值然后根据该值生成一个数字。

For the sample code to work, you can try要使示例代码正常工作,您可以尝试

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println("My favorite number is ", rand.Intn(10))
}

time.Now().UnixNano can give an arbitrary(like) number as the value is in 'one thousand-millionth of a second' time.Now().UnixNano 可以给出任意(类似)的数字,因为该值以“千分之一秒”为单位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM