如何在 Java 中生成特定范围内的随机整数? [英] How do I generate random integers within a specific range in Java?

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

问题描述

如何生成特定范围内的随机 int 值?

How do I generate a random int value in a specific range?

我尝试了以下方法,但这些方法不起作用:

I have tried the following, but those do not work:

尝试 1:

randomNum = minimum + (int)(Math.random() * maximum);

错误:randomNum 可能大于 maximum.

尝试 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

错误:randomNum 可能小于 minimum.

推荐答案

请注意,这种方法比 nextInt 方法更偏向且效率更低,https://stackoverflow.com/a/738651/360211

Note that this approach is more biased and less efficient than a nextInt approach, https://stackoverflow.com/a/738651/360211

实现这一目标的一种标准模式是:

One standard pattern for accomplishing this is:

Min + (int)(Math.random() * ((Max - Min) + 1))

Java 数学库函数 Math.random() 生成双精度值在 [0,1) 范围内.请注意,此范围不包括 1.

The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

为了首先获得特定范围的值,您需要乘以您想要覆盖的值范围的大小.

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

Math.random() * ( Max - Min )

这将返回 [0,Max-Min) 范围内的值,其中不包括Max-Min".

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

例如,如果你想要[5,10),你需要覆盖五个整数值,所以你使用

For example, if you want [5,10), you need to cover five integer values so you use

Math.random() * 5

这将返回 [0,5) 范围内的值,其中不包括 5.

This would return a value in the range [0,5), where 5 is not included.

现在您需要将此范围向上移动到您的目标范围.您可以通过添加最小值来完成此操作.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

Min + (Math.random() * (Max - Min))

您现在将获得 [Min,Max) 范围内的值.按照我们的例子,这意味着 [5,10):

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

5 + (Math.random() * (10 - 5))

但是,这仍然不包括 Max 并且您得到的是双倍值.为了包含 Max 值,您需要在范围参数 (Max - Min) 中加 1,然后通过转换为 int 截断小数部分.这是通过以下方式完成的:

But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

Min + (int)(Math.random() * ((Max - Min) + 1))

这就给你了.[Min,Max] 范围内的随机整数值,或根据示例 [5,10]:

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))

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

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