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))
}
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With