java 如何使用 Math.random() 获取范围内的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35488619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:11:17  来源:igfitidea点击:

How to get a random number in a range using Math.random()

javamathrandom

提问by Tariq Al-Attrash

I'm not too familiar with Math.random();and I don't know what to do for the conditions that I want. I want to produce a random integer between 0 and 52 so far this is what I have set up.

我不太熟悉,Math.random();我不知道该怎么办我想要的条件。到目前为止,我想生成一个介于 0 和 52 之间的随机整数,这是我设置的。

    public class Tester{
    public static void main(String args[]){
        int size=52;
        while(size>0){
            int rando=(int)Math.random()*size;
            size--;
            System.out.println(rando);
        }
    }
}

My code prints out all 0's until the condition of the while loop is met. I wanted to know how I would produce a random integer between 0 and 52. I understand that Math.random();produces a double and I think theres a problem with the type casting. Thanks.

我的代码打印出所有的 0,直到满足 while 循环的条件。我想知道如何生成 0 到 52 之间的随机整数。我知道这Math.random();会生成双精度值,我认为类型转换存在问题。谢谢。

回答by osanger

You only cast Math.random(). Its a value between 0 and 1 (excluding 1). If you cast this it's zero anyway.

你只投 Math.random()。它的值介于 0 和 1 之间(不包括 1)。如果你投这个它无论如何都是零。

Cast the whole expression: (int)(Math.random()*size);

投射整个表达式: (int)(Math.random()*size);

BTW: Your interval is only from 0 to 51 (because of the excluding 1.

顺便说一句:你的间隔只是从 0 到 51(因为不包括 1。

Use (int)(Math.random()*(size+1));, if you want 0...52 as your interval.

使用(int)(Math.random()*(size+1));, 如果您想要 0...52 作为您的间隔。

回答by Mureinik

The cast takes precedence over the multiplication. Since Math.random()returns a double in the range [0.0..1.0), it will always be converted to 0, and the result of multiplying that by any other intwill of course be 0. You could perform the multiplication before casting - ((int)(Math.random()*size)), but really it'd be easier to use Random.nextInt(int).

强制转换优先于乘法。由于Math.random()返回 [0.0..1.0) 范围内的双精度值,它将始终转换为0,并且将其乘以任何其他值的结果int当然是0。您可以在转换 - ( (int)(Math.random()*size))之前执行乘法运算,但实际上使用Random.nextInt(int).

回答by star2wars3

Math.random() returns a pseudo-random number with a domain of [0 , 1).

Math.random() 返回一个域为 [0 , 1) 的伪随机数。

In the line:

在行中:

int rando=(int)Math.random()*size;

this value is cast as an int and then multiplied by size. To fix the problem with only printing zeros you need to add parentheses.

这个值被转换为一个整数,然后乘以大小。要解决仅打印零的问题,您需要添加括号。

int rando = (int) (Math.random()*size);

This will only give you numbers in the domain [0, 51) To fix this:

这只会给你域 [0, 51) 中的数字来解决这个问题:

int rando = (int) (Math.random()* (size + 1);

回答by Douglas Ribeiro

Necessary to use the Math class?

有必要使用 Math 类吗?

a simpler way to find this number would using the Random class

找到这个数字的更简单的方法是使用 Random 类

Example:

例子:

Random randomNumber = new Random ();
System.out.println(randomNumber.nextInt(53));

See also:

也可以看看:

Math.random() versus Random.nextInt(int)

Math.random() 与 Random.nextInt(int)

回答by Supahupe

You can use another code like java.util.Random:

您可以使用其他代码,如 java.util.Random:

Random r = new Random();
int rando = r.nextInt(53); //inclusive 0 and exclusive 53

In case of Math.random() and your code, you have to cast after the multiplication (set the brackets like below):

对于 Math.random() 和您的代码,您必须在乘法之后进行转换(设置如下方括号):

int rando = (int)(Math.random() * size);

In your code, the return value of Math.random() gets casted first and then it is multiplied with the size-parameter. Because Math.random() return double between 0 and 1, the cast to int returns 0.

在您的代码中, Math.random() 的返回值首先被转换,然后与 size-parameter 相乘。因为 Math.random() 返回介于 0 和 1 之间的双精度值,所以转换为 int 会返回 0。

回答by fill?pant?

You cannot use Math.random() to generate a random integer within a range of numbers, as seen in the docs.
But you may use the Randomclass comming in the java.utilpackage, and use the method .nextInt()or more specifically .nextInt(int maximum)where maximum will be 53, not 52 because as docsstate, the method is exclusive.
If you want a number between a specific range like 10 and 50, you may construct a method like this:

您不能使用 Math.random() 生成一个数字范围内的随机整数,如文档中所示
但是您可以使用包中的Randomjava.util,并使用该方法.nextInt()或更具体地说.nextInt(int maximum),其中最大值为53,而不是 52 ,因为作为文档状态,该方法是独占的。
如果您想要一个介于 10 和 50 等特定范围之间的数字,您可以构造一个这样的方法:

 private final Random RANDOMISER = new Random();

 private int generateRandomNumber(int from, int to){
  return RANDOMISER.nextInt((to+1)-from)+from;
 }