Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java random number

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?

like image 729
ErezBerez Avatar asked Jul 20 '26 05:07

ErezBerez


2 Answers

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.

like image 155
Gaël J Avatar answered Jul 22 '26 19:07

Gaël J


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
like image 45
Davide Lorenzo MARINO Avatar answered Jul 22 '26 19:07

Davide Lorenzo MARINO