Go rand.Intn相同的数字/值 [英] Go rand.Intn same number/value

查看:1124
本文介绍了Go rand.Intn相同的数字/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以在这里告诉我为什么使用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个原因:

  1. 您必须初始化由<使用的全局 Source a href ="https://golang.org/pkg/math/rand/#Intn" rel ="noreferrer"> rand.Intn()rand包的其他功能,使用

  1. You have to initalize the global Source used by rand.Intn() and other functions of the rand package using rand.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之类的顶级函数使用默认的共享源,该源每次运行程序时都会产生确定的值序列.如果每次运行需要不同的行为,请使用种子函数初始化默认的源.

  • 旅游为什么count ++(而不是count = count + 1)会改变在Golang中返回地图的方式.

  • 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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆