为什么 (int) Math.random()*10 在 Java 中不产生 10?

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

Why doesn't (int) Math.random()*10 produce 10 in Java?

java

提问by shin

Why the following produce between 0 - 9 and not 10?

为什么以下产生 0 - 9 而不是 10?

My understanding is Math.random() create number between 0 to under 1.0.

我的理解是 Math.random() 创建 0 到 1.0 以下的数字。

So it can produce 0.99987 which becomes 10 by *10, isn't it?

所以它可以产生 0.99987 乘以 *10 变成 10,不是吗?

int targetNumber = (int) (Math.random()* 10);

采纳答案by Greg Hewgill

Casting a doubleto an intin Java does integer truncation. This means that if your random number is 0.99987, then multiplying by 10 gives 9.9987, and integer truncation gives 9.

在 Java 中将a 转换double为 anint会进行整数截断。这意味着如果你的随机数是 0.99987,那么乘以 10 得到 9.9987,整数截断得到 9。

回答by Thariama

Cause (Math.random()* 10gets rounded down using int(), so int(9.9999999)yields 9.

原因(Math.random()* 10使用int()向下取整,因此int(9.9999999)产生9

回答by Kobi

Because (int)rounds down.
(int)9.999results in 9. //integer truncation

因为(int)四舍五入。
(int)9.999结果为 9. //整数截断

回答by Agemen

From the Math javadoc :

从数学 javadoc :

"a pseudorandom double greater than or equal to 0.0 and less than 1.0"

“大于或等于 0.0 且小于 1.0 的伪随机双精度数”

1.0 is not a posible value with Math.random. So you can't obtain 10. And (int) 9.999 gives 9

1.0 不是 Math.random 的可能值。所以你不能得到 10。而 (int) 9.999 给出 9

回答by user207421

0.99987 which becomes 10 by *10

由*10变成10的0.99987

Not when I went to school. It becomes 9.9987.

我上学的时候没有。变成 9.9987。

回答by Paulo Sandsten

Math.floor(Math.random() * 10) + 1

Math.floor(Math.random() * 10) + 1

Now you get a integer number between 1 and 10, including the number 10.

现在你得到一个 1 到 10 之间的整数,包括数字 10。

回答by arsb48

You could always tack on a +1 to the end of the command, allowing it to add 1 to the generated number. So, you would have something like this:

你总是可以在命令的末尾加上 +1,让它在生成的数字上加 1。所以,你会有这样的事情:

int randomnumber = ( (int)(Math.random( )*10) +1);

This would generate any integer between 1 and 10.

这将生成 1 到 10 之间的任何整数。

If you wanted any integer between 0 and 10, you could do this:

如果你想要 0 到 10 之间的任何整数,你可以这样做:

int randomnumber = ( (int)(Math.random( )*11) -1);

Hope this helps!

希望这可以帮助!

回答by ShaT?a S Abú ?l-Rúb

you can add 1 to the equation so the output will be from 1 to 10 instead of 0 to 9 like this :

您可以将 1 添加到等式中,因此输出将从 1 到 10 而不是 0 到 9,如下所示:

int targetNumber = (int) (Math.random()* 10+1);