Thread: randomize

  1. #1
    Unregistered
    Guest

    randomize

    \hey everyone.. i'm looking it up, and i can find ways to randomize a number from 0 to whatever, but how do you get a random number from lets say -500 to 500?

    any help would be appreciated, thanks

  2. #2
    Ethereal Raccoon Procyon's Avatar
    Join Date
    Aug 2001
    Posts
    189
    Try this:

    Code:
    int R(int min, int max)
    {
       return (rand() % (max - min)) + min;
    }

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    412
    That code you posted gives a rand from min to max-1.

    If you input, say, 0 as min, and 10 as max, it would be equal to rand()%10 + 0 -> which gives 0-9, not 1-10.

    To get a number between min and max inclusive, use this:

    Code:
    int R(int min, int max){
         return (rand() % (max + 1 - min)) + min;
    }

  4. #4
    Ethereal Raccoon Procyon's Avatar
    Join Date
    Aug 2001
    Posts
    189
    True. Whether you want inclusive or exclusive on either or both ends depends on the application, I suppose, but probably it's most logical to include that extra +1, as you probably wouldn't want R(0,1) to always return zero.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. randomize array blackjack c program
    By bazzano in forum C Programming
    Replies: 4
    Last Post: 09-01-2005, 02:05 PM
  2. don't want to randomize two alike numbers
    By randomizer in forum C++ Programming
    Replies: 8
    Last Post: 05-26-2005, 07:42 PM
  3. randomize hex digits
    By wazilian in forum C Programming
    Replies: 3
    Last Post: 12-14-2002, 03:20 AM
  4. Problem with Visual C++ ( randomize function )!
    By marCplusplus in forum C++ Programming
    Replies: 2
    Last Post: 12-17-2001, 01:01 PM
  5. Randomize Number Function
    By beyonddc in forum C Programming
    Replies: 3
    Last Post: 12-10-2001, 04:31 AM