Go rand.Intn相同的数字/值 [英] Go rand.Intn same number/value
问题描述
任何人都可以在这里告诉我为什么使用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
包的其他功能,使用
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
:
诸如Float64和Int之类的顶级函数使用默认的共享源,该源每次运行程序时都会产生确定的值序列.如果每次运行需要不同的行为,请使用种子函数初始化默认的源.
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相同的数字/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!