不廢話了,直接上代碼:
package main import ( "fmt" "math/rand" ) func main() { fmt.Println(rand.Intn(100)) fmt.Println(rand.Intn(100)) }
運行測試一下,
$ go run rand.go
81
87
OK,看似沒問題,但再運行一次看看:
$ go run rand.go
81
87
輸出的結果完全一樣,查看官網上的例子:
package main import ( "fmt" "math/rand" ) func main() { rand.Seed(42) // Try changing this number! 注意,注意,注意,重要的事情說三遍 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", } fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))]) }
我這邊運行輸出如下:
Magic 8-Ball says: As I see it yes
多運行幾次,輸出結果不變。按照注釋中說的,修改rand.Seed(42),隨便改這里的值:rand.Seed(2),結果如下:
Magic 8-Ball says: Most likely
多運行幾次還是不變,所以關鍵在rand.Seed()這里,查看文檔:
func (r *Rand) Seed(seed int64)
Seed uses the provided seed value to initialize the generator to a deterministic state.
Seed使用提供的seed值將發生器初始化為確定性狀態。不是很理解這句話的意思,修改一下一開始的代碼試試:
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) fmt.Println(rand.Intn(100)) fmt.Println(rand.Intn(100)) }
$ go run rand.go
9
46
$ go run rand.go
78
98
OK,每次運行產生的輸出不一樣了。
幾點注意項:
1、如果不使用rand.Seed(seed int64),每次運行,得到的隨機數會一樣,程序不停止,一直獲取的隨機數是不一樣的;
2、每次運行時rand.Seed(seed int64),seed的值要不一樣,這樣生成的隨機數才會和上次運行時生成的隨機數不一樣;
3、rand.Intn(n int)得到的隨機數int i,0 <= i < n。
---------------------