C++ random function return same numbers [duplicate

2019-09-22 08:28发布

问题:

This question already has an answer here:

  • Why do I get the same result with rand() every time I compile and run? 4 answers
  • rand() returns same values when called within a single function 5 answers
  • rand() generating the same number [duplicate] 3 answers

I'm trying to get random numbers on range from 0 to 3. Using such code:

#include <cstdlib>
int index = rand() % 3;

But always getting the same results: 1 1 0 1.

What I'm doing wrong? Always the same numbers. Results should change their values after each compilation or during runtime?

回答1:

Your forgot to ad

#include <ctime>
srand(time(NULL)) 

at the start of your program.

This will generate a new seed everytime you run your program based on the current time.



回答2:

Results should change their values after each compilation or during runtime?

Actually, no, the results are supposed to be the same for a given seed, and if you do not set the seed explicitly with srand(), then the results will be the same each time you run. To get different results each time, you should set the seed using something derived from something not completely deterministic, like the time (not deterministic in the sense that you don't know the exact time at the moment it gets used to set the seed).



标签: c++ random