问题
I'm working on an application. I'm using:
int rand_num = rand() % 100;
To get a random integer between 0 to 99. Now, let's say I got 41, then restarting my application, it's always 41. Same sequence over and over, means it's not really random.
Any solutions?
回答1:
rand
generates a pseudo-random number, yes. But you can set the seed.
srand(time(NULL));
int rand_num = rand() % 100;
Set the seed only once.
Or you can use one of the methods from <random>.
回答2:
You have to randomize the seed by calling srand(...) (usually with time(0)
) whenever you start your application. Note that it is a pseudo-random number generator i.e. the values generated by the rand()
function are not uniformly distributed.
回答3:
Correct. rand() returns a pseudo-random number. The sequence from a given start is deterministic. You can alter the starting point using srand().
回答4:
Use the following:
#include<time.h>
srand(time(NULL));
It will change the seed of pseudo-random generator.
For more information see this.
来源:https://stackoverflow.com/questions/14849866/c-rand-is-not-really-random