rand() return the same number [duplicate]

2019-02-26 04:48发布

问题:

This question already has an answer here:

  • srand() — why call it only once? 7 answers

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

回答1:

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



回答2:

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.)



标签: c random srand