shin
shin

Reputation: 32721

Why doesn't (int) Math.random()*10 produce 10 in Java?

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);

Upvotes: 7

Views: 39238

Answers (8)

Shatha AR
Shatha AR

Reputation: 15

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);

Upvotes: 0

arsb48
arsb48

Reputation: 563

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!

Upvotes: 0

Paulo Sandsten
Paulo Sandsten

Reputation: 1

Math.floor(Math.random() * 10) + 1

Now you get a integer number between 1 and 10, including the number 10.

Upvotes: 0

Kobi
Kobi

Reputation: 138027

Because (int) rounds down.
(int)9.999 results in 9. //integer truncation

Upvotes: 1

user207421
user207421

Reputation: 310956

0.99987 which becomes 10 by *10

Not when I went to school. It becomes 9.9987.

Upvotes: 0

Agemen
Agemen

Reputation: 1535

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

Upvotes: 14

Greg Hewgill
Greg Hewgill

Reputation: 993303

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.

Upvotes: 19

Thariama
Thariama

Reputation: 50832

Cause (Math.random()* 10 gets rounded down using int(), so int(9.9999999) yields 9.

Upvotes: 2

Related Questions