打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
golang随机数生成踩过的坑记录一下

不废话了,直接上代码:

package main import ( 'fmt' 'math/rand' ) func main() { fmt.Println(rand.Intn(100)) fmt.Println(rand.Intn(100)) }

运行测试一下,
$ go run rand.go
81
87

OK,看似没问题,但再运行一次看看:

$ go run rand.go
81
87

输出的结果完全一样,查看官网上的例子:

package main

import (
'fmt'
'math/rand'
)

func main() {
rand.Seed(42) // Try changing this number! 注意,注意,注意,重要的事情说三遍
answers := []string{
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes definitely',
'You may rely on it',
'As I see it yes',
'Most likely',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
'Don't count on it',
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful',
}
fmt.Println('Magic 8-Ball says:', answers[rand.Intn(len(answers))])
}

我这边运行输出如下:
Magic 8-Ball says: As I see it yes
多运行几次,输出结果不变。按照注释中说的,修改rand.Seed(42),随便改这里的值:rand.Seed(2),结果如下:
Magic 8-Ball says: Most likely
多运行几次还是不变,所以关键在rand.Seed()这里,查看文档:
func (r *Rand) Seed(seed int64)
Seed uses the provided seed value to initialize the generator to a deterministic state.
Seed使用提供的seed值将发生器初始化为确定性状态。不是很理解这句话的意思,修改一下一开始的代码试试:

package main import ( 'fmt' 'math/rand' 'time' ) func main() { rand.Seed(time.Now().Unix()) fmt.Println(rand.Intn(100)) fmt.Println(rand.Intn(100)) }

$ go run rand.go

9
46
$ go run rand.go
78
98


OK,每次运行产生的输出不一样了。

几点注意项:

1、如果不使用rand.Seed(seed int64),每次运行,得到的随机数会一样,程序不停止,一直获取的随机数是不一样的;

2、每次运行时rand.Seed(seed int64),seed的值要不一样,这样生成的随机数才会和上次运行时生成的随机数不一样;

3、rand.Intn(n int)得到的随机数int i,0 <= i < n。
---------------------

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
随机数,数字解析,URL解析
go语言学习笔记 | Golang中文社区(Go语言构建) | Go语言中文网 | Go语言学习园地
Go操作Redis实战
go协程全局变量和局部变量
Go语言入门指南,带你轻松学Go
golang中net/http包的简单使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服