C++ randomized number always same even with time(0

2019-09-21 04:23发布

问题:

This question already has an answer here:

  • How to generate different random numbers in a loop in C++? 13 answers

Hi I'm trying to generate some random numbers which will be converted to chars later. The problem is the number generated by rand() always return the same although I've used time(0) as the seed for the rand().

int randomNumber(int min, int max)
{
    srand(time(0)); 
    int rndm = (rand()%(max-min))+min;
    cout<<rndm<<" ";
    return 0;
}

Let's say I generate the random 3 times

int main()
{
    randomNumber(0,5);
    randomNumber(0,5);
    randomNumber(0,5);
}

The numbers produced will be 1 1 1 or 2 2 2 etc. Any idea? Thanks

回答1:

You're reseeding the pseudo-random sequence with the same seed before each call to rand, since the value returned by time only changes once a second. That causes you to get the same result each time.

Only call srand once, at the start of the program.

Better still, look at the C++11 <random> library, which has more sophisticated generators and access to "true" random numbers for seeding them.



标签: c++ random