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);
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.
Because (int)
rounds down.
(int)9.999
results in 9.
//integer truncation
0.99987 which becomes 10 by *10
Not when I went to school. It becomes 9.9987.
Math.floor(Math.random() * 10) + 1
Now you get a integer number between 1 and 10, including the number 10.
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:
int randomnumber = ( (int)(Math.random( )*10) +1);
This would generate any integer between 1 and 10.
If you wanted any integer between 0 and 10, you could do this:
int randomnumber = ( (int)(Math.random( )*11) -1);
Hope this helps!
you can add 1 to the equation so the output will be from 1 to 10 instead of 0 to 9 like this :
int targetNumber = (int) (Math.random()* 10+1);