Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

6.5 Random number

Image result for rand() logo
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;
}

                      7.1 Function Basics          NEXT >>

Post a Comment