C program - srand() [duplicate]

2019-01-12 13:01发布

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?

标签: c srand
6条回答
Emotional °昔
2楼-- · 2019-01-12 13:11

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);
查看更多
男人必须洒脱
3楼-- · 2019-01-12 13:13

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-01-12 13:16

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.

查看更多
来,给爷笑一个
5楼-- · 2019-01-12 13:16

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 ) ) );
查看更多
Anthone
6楼-- · 2019-01-12 13:18

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

Just initialize it outside the loop, once.

查看更多
乱世女痞
7楼-- · 2019-01-12 13:21

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;

查看更多
登录 后发表回答