C program - srand() [duplicate]

2019-01-12 13:04发布

问题:

Possible Duplicate:
Recommended way to initialize srand?

I have the following problem when using srand() in c.

I call srand(time(NULL)) in a loop, but the loop finishes before 1 sec and every time I call the rand() I get the same value.

How can I solve this?

回答1:

because the seed is bound into the time() which are seconds since unix epoch, basically you're giving it the same seed because the loop takes less than a second.

What you should do is get the time in microseconds. Take a look at gettimeofday() if you're coding for windows google microseconds win32 C, you mind need to convert it from double to integerso just do this (unsigned int)double * 100.0f;



回答2:

Why are you calling srand in a loop? Just call it once at the start of your program and then call rand any number of times.



回答3:

Don't call srand in the loop. Why are you doing this?

Just initialize it outside the loop, once.



回答4:

You just need to initialize srand() once, then you just need to use rand() to generate the random numbers. And to generate random numbers use Better random algorithm?

If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) ( 10.0 * ( rand() / ( RAND_MAX + 1.0 ) ) );


回答5:

srand's purpose is to initialize the random number generator.

Its parameter is called a seed. If you give the same seed twice, you can expect the random number generator (subsequent calls to rand()) to return the same sequence of "random" numbers.

In your case you're constantly calling srand with the same value (until the second changes), so rand() will always return you the same value.

You just need to call srand once.



回答6:

I found the answer with your help.

        struct timeval tv;
        gettimeofday(&tv,NULL);
        unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;//find the microseconds for seeding srand()
        srand(time_in_micros);


标签: c srand