GolangNote

Golang笔记

golang 以时间戳为种子生成随机数的代码

Permalink

生成随机数可用math/rand包,时间戳引用time包,下面以时间戳为种子生成随机数的代码。

golang 以时间戳为种子生成随机数的代码

Go: 随机数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    fmt.Println(time.Now().Unix(), time.Now().UnixNano())
    r := rand.New(rand.NewSource(time.Now().Unix()))
    for i := 0; i < 10; i++ {
        fmt.Println(r.Intn(100))
    }
}

上面的例子会输出0~99 的随机整数

plaintext: 随机数输出
1
2
3
4
5
6
7
8
9
10
11
1440384388 1440384388207838564
15
68
8
83
35
67
0
66
36
84

每次运行的结果都不一样。

本文网址: https://golangnote.com/topic/25.html 转摘请注明来源

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Golang sync.WaitGroup 的 Wait 超时处理

sync.WaitGroup 使用 `Add(1)`、`Done()`、`Wait()`组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。...

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

Write a Comment to "golang 以时间戳为种子生成随机数的代码"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms