java Math.random() 生成一个介于 1 和 2 之间的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21246696/
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-08-13 07:38:26  来源:igfitidea点击:

Generating a number between 1 and 2 java Math.random()

javamathrandom

提问by zeck

I'm working on creating a range of numbers between 1 and 2 using the imported math.random() class.

我正在使用导入的 math.random() 类创建 1 到 2 之间的一系列数字。

Here's how I got it working so far, however I can't see how it would work:

到目前为止,这是我如何让它工作的,但是我看不出它是如何工作的:

int tmp = (int)(Math.random()*1)+1;

Anyonould?e know if that actually works to get the range? if not.. then what

任何人都知道这是否真的有效以获得范围?如果没有..那怎么办

EDIT: Looking for either the number 1 or 2.

编辑:寻找数字 1 或 2。

回答by poitroae

int tmp = (int) ( Math.random() * 2 + 1); // will return either 1 or 2

Math.random()returns numbers from [0, 1). Because (int)always rounds down (floors), you actually want the range [1,3), so that [1,2)will be rounded to 1 and [2,3)will be rounded to 2.

Math.random()从 返回数字[0, 1)。因为(int)总是向下舍入(地板),您实际上需要 range [1,3),因此[1,2)将舍入为 1 并将[2,3)舍入为 2。

回答by pjs

If you want the values 1 or 2 with equal probability, then int temp = (Math.random() <= 0.5) ? 1 : 2;is all you need. That gives you a 1 or a 2, each with probability 1/2.

如果您希望值 1 或 2 的概率相等,那么这int temp = (Math.random() <= 0.5) ? 1 : 2;就是您所需要的。这给你一个 1 或 2,每个都有 1/2 的概率。

回答by Raul Guiu

Ok, you want to use Math.random, but you could use java.util.Randomso no casting or rounding is required:

好的,您想使用Math.random,但您可以使用,java.util.Random因此不需要强制转换或舍入:

    java.util.Random random = new java.util.Random();
    int tmp = random.nextInt(2) + 1;

回答by peter.petrov

Try this.

尝试这个。

int tmp = (int)( Math.floor( Math.random() + 1.5 ) )

Math.random() -> [0, 1)

Math.random() -> [0, 1)

Math.random() + 1.5 -> [1.5, 2.5)

Math.random() + 1.5 -> [1.5, 2.5)

So when you take the floor, it is either 1 or 2 with equal
probability because [1.5, 2.5) = [1.5, 2) U [2, 2.5)
and length([1.5, 2)) = length([2, 2.5)) = 0.5.

所以当你发言时,它是 1 或 2 的
概率相等,因为[1.5, 2.5) = [1.5, 2) U [2, 2.5)
length([1.5, 2)) = length([2, 2.5)) = 0.5