|
-
Feb 22nd, 2010, 07:42 PM
#1
Thread Starter
Fanatic Member
Random number between 0 and 2
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
-
Feb 23rd, 2010, 03:12 AM
#2
Re: Random number between 0 and 2
int x = 1+(int)(Math.random()*2);
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Feb 23rd, 2010, 12:35 PM
#3
Thread Starter
Fanatic Member
Re: Random number between 0 and 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
-
Feb 23rd, 2010, 02:32 PM
#4
Re: Random number between 0 and 2
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.
Code:
int x = (int)(Math.random()*3);
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|