random number in c++

C (and by extension C++) comes with a built-in pseudo-random number generator. It is implemented as two separate functions that live in the cstdlib header:

srand() sets the initial seed value. srand() should only be called once.
rand() generates the next random number in the sequence (starting from the seed set by srand()).

Here’s a sample program using these functions:
int main()
{
int count;
srand(5323);
// set initial seed value to 5323

// Print 10 random numbers
for (i=0; i < 10; i++)
{
cout << rand() << “\t”;
}
}

The output of this program will be any 10 numbers.

The range of rand()

rand() generates pseudo-random integers between 0 and RAND_MAX, a constant in stdlib that is typically set to 32767.

Generally, we do not want random numbers between 0 and RAND_MAX — we want numbers between two other values, which we’ll call Low and High.
For example, if we’re trying to simulate the user rolling a dice, we want random numbers between 1 and 6.

It turns out it’s quite easy to take the result of rand() can convert it into whatever range we want:
// Generate a random number between Low and High (inclusive)
unsigned int GetRandomNumber(int Low, int High)
{
return (rand() % (High – Low + 1)) + Low;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s