C++: Rand()
Repeat Random Number
Often we will need to generate random numbers, since it would be extremely difficult to generate truly random numbers, we will settle for pseudo-random numbers which will suit your needs most of the time. To generate these we can use the C++ rand() function. Here is an example of using the rand function:
#include <iostream>
using namespace std;
int main(){
for(int loop = 0; loop < 10; ++loop){
cout << rand() << endl;
}
system("PAUSE");
return 0;
}
DownloadTime Rand
However as you may have noticed, if you run the application more than once, it generated the same "random" numbers. This is usually not what we want, so to fix this we set the starting point for generating random numbers to a different value each time the application is run. A good way to use this is to use the time, we don't really care what the time is we simply use it to generate the random numbers. Here is a random number generator that uses the time to generate the random numbers:
#include <iostream>
#include <ctime>
using namespace std;
int main(){
time_t t;
time(&t);
srand(t);
for(int loop = 0; loop < 10; ++loop){
cout << rand() << endl;
}
system("PAUSE");
return 0;
}
Download#include <ctime>This includes the file needed for time related things.
time_t t;Creates a time variable called t
time(&t);Stores the time in t
srand(t);Makes the time, the seed for the random operations.
If you really wanted to mix things up a bit you could use mathematical operations on the seed like so:
srand(t*2);
RAND_MAX
The rand function generates any number from 0 to rand_max, we can find rand_max by using a program like this:
#include <iostream>
using namespace std;
int main(){
cout << RAND_MAX << endl;
system("PAUSE");
return 0;
}
DownloadMy RAND_MAX is 32767 but it can vary from system to system.
Some of the time you will want to generate random numbers within a certain range, to do this we specify a modulus (when a modulus is specified the maximum that the numbers will generate is the modulus minus one). To specify a modulus we would change this line in the timerand program:
cout << rand() << endl;
to some thing like this (in this case 7 is the modulus):
cout << (rand() % 7) << endl;
Back to C++

