在Go中生成一定范围内的随机数 [英] Generating random numbers over a range in Go

查看:1016
本文介绍了在Go中生成一定范围内的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

math/rand 中的所有整数函数都生成非负数.

All the integer functions in math/rand generate non-negative numbers.

rand.Int() int              // [0, MaxInt]
rand.Int31() int32          // [0, MaxInt32]
rand.Int31n(n int32) int32  // [0, n)
rand.Int63() int64          // [0, MaxInt64]
rand.Int63n(n int64) int64  // [0, n)
rand.Intn(n int) int        // [0, n)

我想生成 [-m,n)范围内的随机数.换句话说,我想产生一个正数和负数的组合.

I would like to generate random numbers in the range [-m, n). In other words, I would like to generate a mix of positive and negative numbers.

推荐答案

我在

I found this example at Go Cookbook, which is equivalent to rand.Range(min, max int) (if that function existed):

rand.Intn(max - min) + min

这篇关于在Go中生成一定范围内的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆