doulai7239 2015-05-14 22:04
浏览 57
已采纳

去随机数总是返回168

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条回答 默认 最新

  • dongsuichi6529 2015-05-14 22:07
    关注

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd
  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt
  • ¥15 STM32阿里云平台显示不了传感器采集的数据