Java中使用Math.random()的随机数

Ale*_*lex 15 java random

为了生成随机数,我使用了公式:

(int)(Math.random() * max) + min

我在Google上找到的公式似乎总是如下:

(int)(Math.random() * (max - min) + min)

哪一个对吗?据我所知,我的公式中从未得到超出我的范围的数字

pjz*_*pjz 16

您的公式会在min和min + max之间生成数字.

谷歌发现的那个产生了最小和最大之间的数字.

谷歌赢了!


Mar*_*ers 11

更好的方法是:

int x = rand.nextInt(max - min + 1) + min;
Run Code Online (Sandbox Code Playgroud)

您的公式在min和之间生成数字min + max.

Random random = new Random(1234567);
int min = 5;
int max = 20;
while (true) {
    int x = (int)(Math.random() * max) + min;
    System.out.println(x);
    if (x < min || x >= max) { break; }
}       
Run Code Online (Sandbox Code Playgroud)

结果:

10
16
13
21 // Oops!!
Run Code Online (Sandbox Code Playgroud)

在这里在线查看:ideone


F.J*_*F.J 6

你的:最低可能是分钟,最高可能是最高+分钟-1

Google:最低可能是分钟,最高可能是max-1

  • 确实如此.因此-1. (2认同)