Why the following produce between 0 - 9 and not 10?
My understanding is Math.random() create number between 0 to under 1.0.
So it can produce 0.99987 which becomes 10 by *10, isn't it?
int targetNumber = (int) (Math.random()* 10);
Casting a double
to an int
in 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.
From the Math javadoc :
"a pseudorandom double greater than or equal to 0.0 and less than 1.0"
1.0 is not a posible value with Math.random. So you can't obtain 10. And (int) 9.999 gives 9
Cause (Math.random()* 10 gets rounded down using int(), so int(9.9999999) yields 9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With