C++ Generate random numbers in Range

Monday, June 8, 2009 17:06
Posted in category C++, Programming

To make use of the rand() command you must include the cstdlib library

#include <cstdlib>

Before we generate a random number we call the srand(int) function to seed the randomizer so we dont get the same random number each time.

#include <ctime>
srand(time(NULL)); // time(NULL) returns seconds since 1.1.1970

To get the random number in range we use:

int number = (rand() % (RangeMax – RangeMin + 1) ) +RangeMin;

rand() returns a number between 0 and RAND_MAX (see libs for definition). Using the modulus operator (rest of division) we can get a number in a specific range. rand() % 10 would produce a number between 0 and 9.

You can leave a response, or trackback from your own site.

Leave a Reply

Connect with Facebook