Golang 如何获取Intn类型的随机数
Go语言通过math/rand包提供内置支持,帮助生成指定类型的随机数。该包实现了伪随机数生成器。这些随机数由源生成,并且每次程序运行时,该源会生成一系列确定性的值。如果您想要用于安全敏感工作的随机数,请使用crypto/rand包。
您可以通过 Intn() 函数从默认源生成 [0,n)的Int类型的非负伪随机数。因此,您需要使用import关键字在程序中添加math/rand包以访问Intn()函数。如果n的值小于等于0,则此方法将引发panic。
语法:
func Intn(n int) int
让我们在下面的示例中讨论这个概念:
示例1:
//演示如何获取Intn类型的随机数
// Golang程序
package main
import (
"fmt"
"math/rand"
)
//主函数
func main() {
// 使用Intn()函数找到Int型随机数
res_1 := rand.Intn(7)
res_2 := rand.Intn(8)
res_3 := rand.Intn(2)
// 显示结果
fmt.Println("随机数1: ", res_1)
fmt.Println("随机数2: ", res_2)
fmt.Println("随机数3: ", res_3)
}
输出:
随机数1: 6
随机数2: 7
随机数3: 1
示例2:
//演示如何获取Intn类型的随机数
// Golang程序
package main
import (
"fmt"
"math/rand"
)
// 函数
func intnrandom(value_1, value_2 int) int {
return value_1 + value_2 + rand.Intn(4)
}
// 主函数
func main() {
// 从Intnrandom()中获取结果
res1 := intnrandom(10, 3)
res2 := intnrandom(44, 59)
res3 := intnrandom(130, 50)
// 显示结果
fmt.Println("结果1: ", res1)
fmt.Println("结果2: ", res2)
fmt.Println("结果3: ", res3)
}
输出:
结果1: 14
结果2: 106
结果3: 183
极客教程