3

I'm trying to understand the logic of the math.random or more specifically what is occurring and or why.

I understand essentially with the code below for example due to java being a 0 based language we start at 0 for indexing, etc.

the below code prints out a value between 0 and 10 inclusive. 11 is exclusive as understood.

int result = (int) (Math.random () * 11); 

My question is why for example if we were to get 0.99 * 10 then = 10.99 Why does the number not round up to 11?

Is this simply by design java will always round down to 0? or am I missing a concept?

Thank you for all your help.

Artiems
  • 53
  • 5

1 Answers1

2

As I mentioned in the comments: Casting to an int will result in a floor. This means that your number will always get rounded to 0, so 10.99 will become 10 after casting to int.

You can look at this reference as well

David Buzatu
  • 624
  • 8
  • 18