In computers, there is no such thing as a "random number" -- only
pseudo-random numbers.
You can choose from a whole collection of pseudo-random number sequences. You do this by seeding the generator using
srand().
You can pick a specific sequence by passing specific integer to the
srand() function, so that every time you run your program it uses the exact same sequence of pseudo-random numbers, yes.
Usually, however, people want the program to behave
differently each time it is run. So you are correct that a relatively random seed must be used. This is where the
time() comes in. What better choice of randomness than the time the user launched the program?
You only need to seed the (P)RNG
once, at the beginning of the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void cast();
int main() {
// Seed the RNG once, at the start of the program
srand( time( NULL ) );
// Roll our die
cast();
// All done
return 0;
}
void cast() {
for (int i = 0; i < 3; i++) {
// Get a pseudo-random number in [1,100]
int num = (rand() % 100) + 1;
cout << num << endl;
}
}
|
Please don't throw random
void and
returns in there.
Hope this helps.