在最小值,最大值之间生成加密随机整数

时间:2014-10-02 02:02:18

标签: random go

我尝试在最小值和最大值之间生成一个随机数, 但似乎我迷失了这个,有什么不对?

package main

import (
    "crypto/rand"
    "encoding/binary"
    "fmt"
)

func genRandNum(min, max int8) int {
    var num int8
    binary.Read(rand.Reader, binary.LittleEndian, &num)
    return int(num*(max-min)+min)
}

func main() {
    // trying to get a random number beetwen -10 and 10
    fmt.Println(genRandNum(-10,10))
}

1 个答案:

答案 0 :(得分:3)

这个怎么样

func main() {
    fmt.Println(genRandNum(-10, 10))
}

func genRandNum(min, max int64) int64 {
    // calculate the max we will be using
    bg := big.NewInt(max - min)

    // get big.Int between 0 and bg
    // in this case 0 to 20
    n, err := rand.Int(rand.Reader, bg)
    if err != nil {
        panic(err)
    }

    // add n to min to support the passed in range
    return n.Int64() + min
}

转到play