gpt4 book ai didi

random - 在最小值、最大值之间生成加密随机整数

转载 作者:IT王子 更新时间:2023-10-29 01:59:48 24 4
gpt4 key购买 nike

我试图生成一个介于最小值和最大值之间的随机数,但似乎我对此迷路了,怎么了?

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))
}

最佳答案

这个怎么样

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

关于random - 在最小值、最大值之间生成加密随机整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com