The rand() function does not return a random number , it returns a pseudo-random number. This is evident when you get the same "random" number sequence every time you run your program. The way to prevent this is to seed the random number generator to produce a different sequence of random numbers. The srand() function seeds the random number generator to the given number. However, if you set the generator to the same seed number every time, you will still get the same sequence of random numbers. That is where the time comes in. Seeding the random number based on the time will give you the best randomness. A simple example:
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
//Notice the use of C++ headers
using namespace std;
int main() {
//Seed random number generator based on time
srand(time(NULL));
for(int i = 0;i < 10;i++)
cout <<rand() <<endl;
}
Notice that it will most likely print off 10 really big numbers. Usually we only want to work with much smaller numbers, like 0-2(for 3 different outcomes). That's where the modulus operator(%) comes in. Hope that helps a little.