英文:
Random number issue in golang
问题
这是我正在使用的代码:
package main
import "fmt"
import "math/rand"
func main() {
code := rand.Intn(900000)
fmt.Println(code)
}
它总是返回 698081
。我不明白,问题是什么?
编辑:
我尝试了 rand.Seed
package main
import "fmt"
import "time"
import "math/rand"
func main() {
rand.Seed(time.Now().UnixNano())
code := rand.Intn(900000)
fmt.Println(code)
}
没有变化。现在它总是返回 452000
英文:
This is the code I'm working with:
package main
import "fmt"
import "math/rand"
func main() {
code := rand.Intn(900000)
fmt.Println(code)
}
It always returns 698081
. I don't understand, what the is problem?
> https://play.golang.org/p/XisNbqCZls
Edit:
I tried rand.Seed
package main
import "fmt"
import "time"
import "math/rand"
func main() {
rand.Seed(time.Now().UnixNano())
code := rand.Intn(900000)
fmt.Println(code)
}
There is no change. Now it always returns 452000
> https://play.golang.org/p/E_Wfm5tOdH
>
> https://play.golang.org/p/aVWIN1Eb84
答案1
得分: 24
以下是要翻译的内容:
有几个原因会导致你在 playground 中看到相同的结果:
- Golang playground 会缓存结果。
- Playground 中的时间始终从相同的时间开始,以使 playground 具有确定性。
最后,rand
包的默认种子是 1
,这将使结果具有确定性。如果你使用 rand.Seed(time.Now().UnixNano())
,每次执行时都会得到不同的结果。请注意,由于上述第二个原因,这在 playground 上不起作用。
英文:
A couple of reasons why you'll see the same result in the playground
- Golang playground will cache the results
- The time in the playground always starts at the same time to make the playground deterministic.
Last but not least, the rand
package default seed is 1
which will make the result deterministic. If you place a rand.Seed(time.Now().UnixNano())
you'll receive different results at each execution. Note that this won't work on the playground for the second reason above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论