golang 隨機數

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport "fmt"import "math/rand"func main() {//例如,rand.Intn 返回一個隨機的整數 n,0 <= n <= 100。    fmt.Print(rand.Intn(100), ",")    fmt.Print(rand.Intn(100))    fmt.Println()//rand.Float64 返回一個64位浮點數 f,0.0 <= f <= 1.0。    fmt.Println(rand.Float64())//這個技巧可以用來產生其他範圍的隨機浮點數,例如5.0 <= f <= 10.0    fmt.Print((rand.Float64()*5)+5, ",")    fmt.Print((rand.Float64() * 5) + 5)    fmt.Println()//要讓偽隨機數產生器有確定性,可以給它一個明確的種子。    s1 := rand.NewSource(42)    r1 := rand.New(s1)//調用上面返回的 rand.Source 的函數和調用 rand 包中函數是相同的。    fmt.Print(r1.Intn(100), ",")    fmt.Print(r1.Intn(100))    fmt.Println()如果使用相同的種子產生的隨機數產生器,將會產生相同的隨機數序列。    s2 := rand.NewSource(42)    r2 := rand.New(s2)    fmt.Print(r2.Intn(100), ",")    fmt.Print(r2.Intn(100))    fmt.Println()}$ go run random-numbers.go 81,870.66456005321849047.123187485356329,8.4341153643355475,875,87

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.