Randomize numbers from -100 to 100!

This is a discussion on Randomize numbers from -100 to 100! within the C++ Programming forums, part of the General Programming Boards category; How is it done? Is this correct? If not why? int nr; nr = rand() % 200 - 100;...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    5

    Randomize numbers from -100 to 100!

    How is it done? Is this correct? If not why?

    int nr;
    nr = rand() % 200 - 100;

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    That depends on exactly what you mean by "randomize number from -100 to 100". To me, that sounds like you want a shuffle routine. However, if you just want a random number in that range (inclusive) then you've almost got it:
    Code:
    nr = rand() % 201 - 100;

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    5
    Thx!

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,307
    Please read the last post here about the ideal way to do this.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Very good point, iMalc. I had noticed a while ago that there was a bias but hadn't thought of a way to fix it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-13-2011, 08:10 PM
  2. randomize in C
    By torquemada in forum C Programming
    Replies: 7
    Last Post: 03-11-2011, 03:59 AM
  3. Randomize (please help
    By jaybo1973 in forum C++ Programming
    Replies: 6
    Last Post: 06-06-2005, 11:56 AM
  4. don't want to randomize two alike numbers
    By randomizer in forum C++ Programming
    Replies: 8
    Last Post: 05-26-2005, 07:42 PM
  5. randomize how to use?
    By erol in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2001, 11:13 AM

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