jjzjj

go - 为什么每次运行程序时 math/rand 包中的 rand.Intn() 函数都会生成相同的随机数序列?

我使用rand.Intn(nint)函数交换slice内的元素,但每次运行该程序时,输出都是slice内相同的随机元素序列。我在这里缺少什么明显的东西? 最佳答案 来自documentationUsetheSeedfunctiontoinitializethedefaultSourceifdifferentbehaviorisrequiredforeachrun.IfSeedisnotcalled,thegeneratorbehavesasifseededbySeed(1).默认情况下,每次运行都会获得相同的种子。您可以使用当前时间

random - 去 rand.Intn 相同的数字/值

谁能告诉我为什么这里是Go示例:https://tour.golang.org/basics/1总是为rand.Intn(10)返回相同的值? 最佳答案 2个原因:你必须初始化全局Source由rand.Intn()使用和rand包的其他函数使用rand.Seed().例如:rand.Seed(time.Now().UnixNano())查看DifficultywithGoRandpackage的可能重复项.引用rand的包文档:Top-levelfunctions,suchasFloat64andInt,useadefaultsh