Usually, we want to generate random numbers within a specific range, rather than between 0 and 32767. The modulus operator, %, is very handy for this. This example generates 5 numbers between 1 and 10:
#include <iostream.h> // for cout
#include <stdlib.h> // for rand()
void main(void)
{
for (int x = 0; x < 5; x++)
cout << setw(5) << rand() % 10 + 1;
}
Output:
7 1 3 1 8
- Each time this program is run, the same 5 numbers will be generated; not very random
- As before, the numbers are not truly random; there is list of "random" integers that provides numbers for each call to rand()
- If you always "start from the beginning" of the list, you will get the same numbers each time
- The idea is to start drawing numbers from a different position in the list each time the program runs; this is called seeding the random number generator