zoukankan      html  css  js  c++  java
  • Golang package之math/rand

    Golang package之math/rand

    概述

    go语言中的随机数应该说是伪随机, math/rand 实现了伪随机数生成器。

    在go语言中随机数需要设置种子,如果不设置种子,随机数每次运行的结果相同,默认种子是1,且相同种子产生的随机数是相同的,为了保证种子不是固定的,可以采用当前时间的纳秒作为种子来生成随机数

    示例1:

    固定种子

    func main() {
        // 固定种子
        rand.Seed(1)
        // Intn(10) 左闭右开区间 [0,10)
        fmt.Println(rand.Intn(10), rand.Intn(10), rand.Intn(10))
        fmt.Println(rand.Intn(10), rand.Intn(10), rand.Intn(10))
        /*
        值始终固定:
            1 7 7
            9 1 8
        */
    }

    示例2:

    使用时间戳产生随机种子

    func main() {
        // 固定种子
        rand.Seed(time.Now().UnixNano())
        // Intn(10) 左闭右开区间 [0,10)
        fmt.Println(rand.Intn(10), rand.Intn(10), rand.Intn(10))
        fmt.Println(rand.Intn(10), rand.Intn(10), rand.Intn(10))
        /*
        值每次都不同:
            8 0 9
            5 5 3
        */
    }
    加油,你们是最棒的!
  • 相关阅读:
    HDU5120
    POJ 1062
    POJ 1086
    BestCoder 1st Anniversary (HDU 5311)
    HDU 5284
    Dylans loves sequence(hdu5273)
    day65 作业
    第三次小组分享 猴子补丁
    day59 csrf auth
    day58 cookie session 中间件
  • 原文地址:https://www.cnblogs.com/Wshile/p/12710674.html
Copyright © 2011-2022 走看看