This is driving me crazy.
I'm expecting this to generate a random number between 0 and 2 in Java.
int x = (int)(Math.random()*2);
However it's only generating 0s and 1s. What am I doing wrong here?
Thanks,
Strick
Printable View
This is driving me crazy.
I'm expecting this to generate a random number between 0 and 2 in Java.
int x = (int)(Math.random()*2);
However it's only generating 0s and 1s. What am I doing wrong here?
Thanks,
Strick
int x = 1+(int)(Math.random()*2);
Hi,
Thanks for you reply. I think when I tried this, I didn't get 0's. I only got 1s and 2s. I'll trying it again to make sure though.
Thanks,
Strick
Since Math.random generates a number in the range 0.0 up to, but not including 1.0. And you're using truncation when casting to an int, you will simply want to have.
This will actually generate any value from 0.0 to 2.99 (as long as it is below 3), but since you're casting to an int, the decimal gets left off. The above code will never give you a 3.Code:int x = (int)(Math.random()*3);