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实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

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

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