rand interval

This is a discussion on rand interval within the C++ Programming forums, part of the General Programming Boards category; looking for the easiest way to generate random numbers ranging from [-64 63] using rand(). can't seem to hack it....

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    3

    rand interval

    looking for the easiest way to generate random numbers ranging from [-64 63] using rand().

    can't seem to hack it.

  2. #2
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,754
    rand()%128 - 64
    To be or not to be == true

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,630
    vart's solution works, but you might also want to read more: using rand()
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    33,292
    Or "gasp, shock, horror", the FAQ
    http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,754
    vart's solution works
    It was provided because
    The first solution only works when N evenly divides into RAND_MAX
    N is 128 in this case and the condition should be fulfilled...
    To be or not to be == true

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,346
    You never answered my question from the last thread. There's a real possibility that you want unique numbers, and getting a random number in the range [-63, 64] is the wrong way to go about that.

  7. #7
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,855
    >N is 128 in this case and the condition should be fulfilled...
    Who said RAND_MAX has to be a power of two?
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21