Results 1 to 4 of 4

Thread: Random number between 0 and 2

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2004
    Posts
    541

    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

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    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

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2004
    Posts
    541

    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

  4. #4
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    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
  •  



Click Here to Expand Forum to Full Width