3

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?

0

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3

Math.random() returns a double number between 0 and 1 exclusive, which means (int)Math.random() will always be 0 (since Math.random() < 1). In order to perform the multiplication before the cast to int, you must use parentheses as you did.

Comments

2

The other answers already explained the issue with your code, so I won't cover this topic here anymore.

This is just a note on the generation of random-numbers:
The recommended way of generating random-numbers in java isn't Math.random() , but via the java.util.Random class (http://docs.oracle.com/javase/7/docs/api/java/util/Random.html).

To generate a random-number like in the above example, you can use this code:

Random rnd = new Random();
int i = rnd.nextInt(10);

, which will produce the same result as your code.

Comments

0
int rand = (int) Math.random()*10;

is equivalent to

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

Considering that Math.random() return a number from 0<=N<1, if you try to cast it you will always get 0, that multiply by 10 is still 0

int rand = ((int) Math.random()); -- ALWAYS --> ZERO

0*N ---- ALWAYS ---> ZERO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.