How to calculate a random number in Go?

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

How to calculate a random number in Go?

问题

以下是翻译好的内容:

package main

import "fmt"

import "math/rand"

func main() {

	var milesdriven float64
	var enginerunningloud bool = true
	var changeoil bool = true

	if milesdriven >= 3000.0 || enginerunningloud == false {

		float64 := (milesdriven * Rand)
		changeoil = true
		fmt.Println("Change that oil duuuuuude")

	}

}

这是我目前的代码,但我一直收到"imported and not used "math/rand""的错误提示,还有一个未定义的Rand是什么意思?我该怎么办?

英文:
package main

import "fmt"

import "math/rand"

func main() {

	var milesdriven float64
	var enginerunningloud bool = true
	var changeoil bool = true

	if milesdriven >= 3000.0 || enginerunningloud == false {

		float64 := (milesdriven * Rand)
		changeoil = true
		fmt.Println("Change that oil duuuuuude")

	}

}

This is what I have so far but I keep getting imported and not used "math/rand" and also a undefined Rand what does that mean? And what should I do?

答案1

得分: 2

请参考math/rand包的文档以了解如何生成随机数。例如:

package main

import "math/rand"
import "time"

func main() {
  seed := time.Now().UnixNano()
  random := rand.New(rand.NewSource(seed))
  println(random.Float64()) // => +8.277637e-001
  println(random.Int())     // => 7112143871403206581
  // etc.
}
英文:

See the math/rand package documentation for how to generate random numbers. e.g.:

package main

import "math/rand"
import "time"

func main() {
  seed := time.Now().UnixNano()
  random := rand.New(rand.NewSource(seed))
  println(random.Float64()) // => +8.277637e-001
  println(random.Int())     // => 7112143871403206581
  // etc.
}

huangapple
  • 本文由 发表于 2015年4月18日 06:50:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/29710685.html
匿名

发表评论

匿名网友

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

确定