英文:
Generating a random variable in golang using math/rand
问题
我正在尝试在golang程序中模拟一个硬币翻转。我尝试使用math/rand
包,并使用time
进行种子初始化。
根据我在其他地方和在线上查找的信息,我的实现应该是正确的:
import (
"fmt"
"math/rand"
"time"
)
func main() {
var random int
var i int
var j int
for j != 5 && i != 5 {
rand.Seed(time.Now().UnixNano())
random = rand.Intn(2)
if random == 0 {
i = i + 1
}
if random == 1 {
j = j + 1
}
}
fmt.Println(i, j)
}
但是,每次运行时,random
总是为0。种子也没有改变,这让我感到困惑。由于它在循环内部,难道不应该每次种子初始化时都改变纳秒级的时间吗?
英文:
I'm trying to simulate a coin flip for a program in golang. I'm trying to use math/rand
and I'm seeding it using time
.
import (
"fmt"
"math/rand"
"time"
)
From what I've looked up elsewhere on here and online, my implementation should work:
func main() {
var random int
var i int
var j int
for j != 5 && i != 5 {
rand.Seed(time.Now().UnixNano())
random = rand.Intn(1)
if random == 0 {
i = i + 1
}
if random == 1 {
j = j + 1
}
}
fmt.Println(i, j)
}
But, each time I run it, random always end up being 0. The seed doesn't change either, which confuses me. Since it's within the loop, shouldn't the time in nanoseconds change each time it's seeded?
答案1
得分: 5
在循环中不要重新播种,只需在一开始播种一次。
rand.Intn(n)
返回的值大于等于0且小于n。因此,rand.Intn(1)
只能返回0,你需要使用rand.Intn(2)
来获取0或1。
修正后的代码:
http://play.golang.org/p/3D9osMzRRb
英文:
Don't reseed in the loop, do it only once.
rand.Intn(n)
returns a value >= 0 and < n. So rand.Intn(1)
can only return 0, you want rand.Intn(2)
to get 0 or 1.
Fixed code:
http://play.golang.org/p/3D9osMzRRb
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论