Program is generating same random numbers on each run? [duplicate]

It’s seeded by time(NULL)

If it is, I can’t see it. In fact, a search for it in your code returns nothing. The default behaviour, if you don’t explicitly seed, is the same as if you had seeded it with the value 1.

You need to explicitly state something like:

srand (time (NULL));

at the start of main somewhere (and make sure you do this once and once only).

Though keep in mind this makes it dependent on the current time – if you start multiple jobs in the same second (or whatever your time resolution is), they’ll start with the same seed.

From the C standard (on which C++ is based for these compatibility features):

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

Leave a Comment