Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder BWiz's Avatar
    Join Date
    Mar 2006
    Location
    Sol System
    Posts
    471
    Thanks
    7
    Thanked 21 Times in 21 Posts

    Best way to select a bounded random number.

    I'm not exactly sure how to approach this problem, but I want to generate a random number, which would be range between 0 - 99. I know that to have a random number, I need to initialize it with a seed, so I chose to seed it with time. However, I don't know how to ensure that the random number falls between 0 - 99.

    Also, is there a better way to do this? And if so, how so? Thanks in advice.
    BWiz :: Happy Coding!
    2006
    2007 2008 2009
    2010 2011
    Irrational numbers make no sense.

  • #2
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    Most languages have a built-in rand() function.

    So, floor(100*rand()) would give you an integer between 0 and 99.

  • #3
    Regular Coder BWiz's Avatar
    Join Date
    Mar 2006
    Location
    Sol System
    Posts
    471
    Thanks
    7
    Thanked 21 Times in 21 Posts
    By using the rand function, I always seem to get the same number. And then using the *100, it just multiplies the random number by 100.

    Any other ideas?
    BWiz :: Happy Coding!
    2006
    2007 2008 2009
    2010 2011
    Irrational numbers make no sense.

  • #4
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    If you keep getting the same random number, then you need to seed the random number generator (usually done with the current time).

    As for multiplication by 100, most rand() functions return a number between 0 and 1. Multiplying by 100 shifts the decimal point over by 2, mapping the original numbers of 0.00... - 0.99... to 0.... - 99....

    Then, you simply call floor to truncate the decimal part, leaving 0-99.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •