红联Linux门户
Linux帮助

linux/windows平台生成随机数的不同方法

发布时间:2017-01-16 14:47:19来源:linux网站作者:sndnvaps
linux平台,使用rand.Seed()
 
//rand_linux.go
package main
import (
"math/rand"
"time"
)
//get the random number in [min, max]
func RandInt64(min, max int64) int64 {
if min >= max || max == 0 {
return max
}
rand.Seed(time.Now().UnixNano())
//fmt.Println(r.Int63n(max-min) + min)
x := rand.Int63n(max-min) + min
//fmt.Println(x)
return x
}
//get the random numer in [min, max]
func RandInt(min, max int) int {
if min >= max || max == 0 {
return max
}
rand.Seed(time.Now().UnixNano())
//x := r.Intn(max-min) + min
x := rand.Intn(max - min) + min
//fmt.Println("RandInt: = ",x)
return x
}
 
windows平台,直接使用 rand.Int63n() 或者 rand.Intn()
 
//rand_windows.go
package main
import (
"math/rand"
)
//get the random number in [min, max]
func RandInt64(min, max int64) int64 {
if min >= max || max == 0 {
return max
}
x := rand.Int63n(max-min) + min
//fmt.Println(x)
return x
}
//get the random numer in [min, max]
func RandInt(min, max int) int {
if min >= max || max == 0 {
return max
}
x := rand.Intn(max - min) + min
//fmt.Println("RandInt: = ",x)
return x
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/27865.html