0

Why does the following code prints just 25?

while(true) {
    int pos = (int) (Math.random() * (26 ));
    if (pos > 24)
        System.out.println(pos);
}

If Math.random() returns a number from 0 to 1 then shouldn't the code above print also 26 (1*26 = 26)?

It-Z
  • 1,961
  • 1
  • 23
  • 33
vasiliu iorgu
  • 109
  • 1
  • 9

1 Answers1

1

Math.random() returns a positive double greater than or equal to 0.0 and less than 1.0.

(int) will truncate doubles, that is - it will remove all the numbers after the decimal point leaving only the integer part - it will not round the number!

Because Math.random() will never be 1, the random number multiplied be 26 will always be lass then 26. So (int) will truncate the 25.xyz , it will remove all the numbers after the decimal point leaving only 25.

That is way you will never get 26.

It-Z
  • 1,961
  • 1
  • 23
  • 33