I understand that Math.random() by itself generates a random double between 0.0 and 1.0, including 0.0 but excluding 1.0. I also understand that casting to an int truncates everything after the decimal without rounding.
What I don't understand is how something like
System.out.println((int)(Math.random() * 27));
can actually produce a random number from 0 through 26. Since Math.random() by itself only produces 0.0 through 0.9, and 9 * 27 is 24.3, it seems like the greatest int the above code should be able to produce is 24. How does this work?
Through searching for answers to this I have discovered that there are better ways to generate random numbers, but the book I am working through describes this particular method, and I'd like to understand how it works.
Aucun commentaire:
Enregistrer un commentaire