Golang 如何获取整数类型的随机数
Go语言提供了内置支持来生成指定类型的随机数,这是通过math/rand包实现的。这个包实现了伪随机数生成器。这些随机数由一个源生成,每当程序运行时,该源就会产生确定性序列的值。如果你想要进行安全敏感的工作,则应该使用crypto/rand包来生成随机数。
你可以使用math/rand包提供的Int()函数从默认源生成非负的整数类型的伪随机数。因此,你需要在你的程序中使用import关键字添加math/rand包来访问Int()函数。
语法:
func Int() int
让我们通过下面的例子来讨论这个概念:
例子 1:
// Golang程序示例
// 如何获取随机数
package main
import (
"fmt"
"math/rand"
)
// 主函数
func main() {
// 使用Int()函数生成整型随机数
res_1 := rand.Int()
res_2 := rand.Int()
res_3 := rand.Int()
// 显示结果
fmt.Println("随机数 1: ", res_1)
fmt.Println("随机数 2: ", res_2)
fmt.Println("随机数 3: ", res_3)
}
输出:
随机数 1: 5577006791947779410
随机数 2: 8674665223082153551
随机数 3: 6129484611666145821
例子 2:
// Golang程序示例
// 随机数的使用
package main
import (
"fmt"
"math/rand"
)
// 函数
func intrandom(value_1, value_2 int) int {
return value_1 + value_2 + rand.Int()
}
// 主函数
func main() {
// 从intrandom()函数获取结果
res1 := intrandom(2, 6)
res2 := intrandom(49, 50)
res3 := intrandom(120, 98)
// 显示结果
fmt.Println("结果 1: ", res1)
fmt.Println("结果 2: ", res2)
fmt.Println("结果 3: ", res3)
}
输出:
结果 1: 5577006791947779418
结果 2: 8674665223082153650
结果 3: 6129484611666146039
极客教程