Beginner question here: I tried creating a random number using this code
int rand = (int) Math.random()*10;
however, i kept receiving 0 as the answer when printing to screen
only after putting parenthesis like so
int rand = (int)(Math.random()*10);
did the number show properly. Can anyone explain the logical reason for this that I missed?
When you write int rand = (int) Math.random()*10, you're actually writing:
int rand = ((int) Math.random()) * 10;
Therefore you get 0 because the random number is between 0 and 1, and casting it to an int makes it equals to 0.
The code
int rand = (int) Math.random()*10;
is equivalent to
int rand = ((int) Math.random()) * 10;
So the value of Math.random() is converted to an int. Because that value is between 0 and 1 (1 excluded) it is converted always to zero.
So
(int) Math.random()*10 --> ((int) Math.random()) * 10 --> 0 * 10 --> 0
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