Why do I have to include this line when I want to generate a random number?

I'm making a high-low game and I need to generate a random number between 1-100.
I got the program working but im curious as to why I have to include some line.
1
2
3
  int i;
  srand(time(0));
  i = rand()%100;

What is the purpose of "srand(time(0));" ?

Also is the way im doing this fine?
The rand() function doesn't give you a random number.

It gives you the next number in a sequence. The sequences are meant to look kind of random to a person looking at them, but they're not random. They're fixed.

There are many different sequences to pick from.

srand() is how you pick which sequence you're going to get numbers from.

Because the time is different each time you run the program, using time(0) to pick which sequence you're using should mean you get a different sequence each time.


Also is the way im doing this fine?

Depends what you're using it for. rand() produces some very bad results. Sequences that really don't look random and cover a very low range of numbers.

If it doesn't matter, sure, it's fine.

If you ever actually do need a sequence that looks a lot more random, don't use rand().
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.
Topic archived. No new replies allowed.