Not quite fine. You want [1..100]. You get [0..99].
Overall, do not learn rand&srand at all.
Learn this instead:
http://www.cplusplus.com/reference/random/uniform_int_distribution/uniform_int_distribution/
Alas, the std::default_random_engine shown in that example may not be good. Mersenne Twister is better:
http://www.cplusplus.com/reference/random/mersenne_twister_engine/mersenne_twister_engine/
Alas, even the std::seed_seq has issues. The truth is that randomness is very complex math. The rand() is ancient, written before the complexity was understood or feasible.
You know roulette wheel? Round shape with tiny cups on the edge and a number in each cup.
Lets make one with numbers in some "random" order. The numbers are printed, so they will never change.
A ball is in some cup. Every time we call
distribution(generator)
(or
rand()
) we lift the ball from a cup, read the number, and put the ball into the
next cup.
By default, when a program starts, the ball is in the "first" cup. Every time you run the program, you will get the exact same numbers in same order, because the wheel will not change.
What is this
seeding?
1 2 3 4 5
|
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 generator( seed );
// or
unsigned seed = time(0);
srand( seed );
|
We move the ball to a cup, whose
index is seed.
We use current time as the index. Therefore, the index does change, and we will read numbers from a different part of the wheel on different runs of the program.
You seed only once per program run.