Go的随机数函数总是返回168。

huangapple go评论85阅读模式
英文:

Go Random number always return 168

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对Go语言完全不了解。

我正在尝试编写一个任意函数,该函数返回两个随机数的和。

我已经粘贴了我的代码,但无法弄清楚为什么它总是返回168!

package main

import (
    "fmt"
    "math/rand"
)

func add(x int, y int) int {
    return x + y
}

var a int = rand.Intn(100)
var b int = rand.Intn(100)

func main() {
    fmt.Println(add(a, b))
}
英文:

I am a complete noob in regards to Go.

I am trying to make a an arbitrary function that returns two random numbers added together.

I have pasted my code below, and cannot figure out why it always returns 168!

package main

import(
    "fmt"
    "math/rand"
)

func add(x int, y int) int{
    return x + y
}

var a int = rand.Intn(100)
var b int = rand.Intn(100)

func main() {
    fmt.Println(add(a, b))
}

答案1

得分: 10

你必须指定种子以获取不同的数字。在文档中有详细说明:

> 顶层函数(如Float64和Int)使用默认的共享源,在每次运行程序时产生确定性的值序列。如果需要每次运行时具有不同的行为,可以使用Seed函数初始化默认的源。

关于Seed的一些参考信息:

> Seed使用提供的种子值将默认的源初始化为确定性状态。如果未调用Seed函数,则生成器的行为就像通过Seed(1)进行了种子化一样。

你可以在go cookbook中看到一个示例:

rand.Seed(time.Now().Unix())

所以总结一下,你将得到类似这样的代码:

package main

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

func add(x int, y int) int{
    return x + y
}


func main() {
    rand.Seed(time.Now().Unix())
    var a int = rand.Intn(100)
    var b int = rand.Intn(100)
    fmt.Println(add(a, b))
}
英文:

You have to specify seed to get different numbers. It is outlined in documentation:

> Top-level functions, such as Float64 and Int, use a default shared
> Source that produces a deterministic sequence of values each time a
> program is run. Use the Seed function to initialize the default Source
> if different behavior is required for each run.

And some reference about Seed

> Seed uses the provided seed value to initialize the default Source to
> a deterministic state. If Seed is not called, the generator behaves as
> if seeded by Seed(1).

And you can see an example in the go cookbook:

rand.Seed(time.Now().Unix())

So wrapping up, you will have something like this:

package main

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

func add(x int, y int) int{
    return x + y
}


func main() {
    rand.Seed(time.Now().Unix())
    var a int = rand.Intn(100)
    var b int = rand.Intn(100)
    fmt.Println(add(a, b))
}

huangapple
  • 本文由 发表于 2015年5月15日 06:04:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/30248237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定