So, does int random = (int) Math.ceil(Math.random() * 5);
return a value of 0,1,2,3,4 rather than 1开发者_运维技巧,2,3,4,5?
I have tried to test this, but it never seems to hit 0 or 5 =x
In theory, Math.random()
will always return a value greater than or equal to 0, and strictly less than 1.
So using (int) Math.ceil(Math.random() * 5)
should actually give you 0, 1, 2, 3, 4, 5. However, any value returned from Math.random()
other than exactly 0 will be give a value of 1 or more after the call to Math.ceil()
- so you will see 0 vanishingly often. (You'll be lucky if you ever see it, but it's definitely possible.) Seeing 5 is easy - you'll get that any time Math.random()
returns a value greater than 0.8.
Is there any reason you're not using Random.nextInt()
instead?
精彩评论