关于Go的rand

package main

import (
	"math/rand"
	"time"
	"fmt"
)

func main()  {
	rand.Seed(time.Now().Unix())
	//seed 的参数不变的话 -> 此程序的运行环境是固定的,因此 rand.Intn 总是会返回相同的数字   ->所以要讲seed的参数一直改变(获取时间)
	fmt.Printf("随机产生的数字是 : %d \n",rand.Intn(100))

	//for i := 0;i < 10 ;i++  {
	//	fmt.Printf("随机产生的数字是 : %d \n",rand.Intn(10))
	//}


	//var flag = false
	//k := 0
	//for flag == false{
	//	k++
	//	fmt.Printf("随机产生的数字是 : %d \n",rand.Intn(10))
	//	for k == 10  {
	//		flag = true
	//	}
	//}

	//fmt.Printf("随机产生的数字是 : %d \n",rand.Intn(10))
}

如果只有rand.Intn的话,由于运行环境不变,会使每次运行产生的随机数永远相同,需要使用到rand.Seed提供种子数,Seed的参数要变化,此处使用获取系统时间

当然,在一次执行中生成多个随机数,不需要种子。随机数的内容由rand.Intn的参数决定

猜你喜欢

转载自blog.csdn.net/weixin_36771395/article/details/80759784