123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 | package mainimport ( "fmt" "math/rand" "time")func main() { randTest() randAnswer()}func randTest() { //1、通过默认的随机数种子获取随机数. //系统默认的rand对象,随机种子默认都是1 fmt.Println(rand.Int()) fmt.Println(rand.Intn(50)) fmt.Println(rand.Float64()) // 2、动态随机种子,生成随机资源,实例化成随机对象,通过随机对象获取随机数 s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) randnum := r1.Intn(10) fmt.Println(randnum) //3、简写形式:动态种子来获取随机数 // [0,10] rand.Seed(time.Now().UnixNano()) fmt.Println(rand.Intn(10)) fmt.Println(rand.Float64()) //[5,11] num := rand.Intn(7) + 5 fmt.Println(num)}func randAnswer() { answers := []string{ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", } rand.Seed(time.Now().UnixNano()) randnum := rand.Intn(len(answers)) fmt.Println("随机回答", answers[randnum])} |
本文链接: https://dreamerjonson.com/2018/12/01/golang-30-rand-package/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。