rand() return the same number [duplicate]

谁说我不能喝 提交于 2019-12-04 04:44:13

问题


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



来源:https://stackoverflow.com/questions/42243397/rand-return-the-same-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!