rand() return the same number [duplicate]

2019-02-26 04:36发布

This question already has an answer here:

I am making a simple example in C with rand() but the function always return the same number despite i am using srand().

This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int generate(int min, int max)
{
    srand(time(NULL));
    return rand() % (max - min + 1) + min;
}

int main()
{
    int i;
    for (i = 0; i < 10; i++)
    {

        printf("Number random %d = %d\n", i, generate(1, 100));
    }

    return 0;
}

Execution :

Number random 0 = 40 Number random 1 = 40 Number random 2 = 40 Number random 3 = 40 Number random 4 = 40 Number random 5 = 40 Number random 6 = 40 Number random 7 = 40 Number random 8 = 40 Number random 9 = 40

标签: c random srand
2条回答
我只想做你的唯一
2楼-- · 2019-02-26 05:00

Repeatedly calling srand ruins the statistical properties of the generator.

Call it no more than once.

(The observed behaviour is caused by time(NULL) returning the same value in every iteration of the loop.)

查看更多
男人必须洒脱
3楼-- · 2019-02-26 05:20

It is because you are reseeding it every time, and as your program probably runs very quickly, your seed value (time()) is the same for each call as it's smallest increment is 1 second.

Try moving srand() into main() instead and call it once

查看更多
登录 后发表回答