Why does my srand(time(NULL)) function generate the same number every time in c? [duplicate]

南笙酒味 提交于 2020-08-19 17:46:42

问题


So I was creating a program that would call a function and return 0 or 1 (0 meaning tails and 1 meaning heads) and then use that to print the outcome of 100 flips.

It seemed simple enough thinking I could use srand(time(NULL)) to seed rand() with constantly varying seeds. Here was my first crack.

#include <stdio.h>
#include <stdlib.h>
int flip();


int main(void) {

    int heads = 0;
    int tails = 0;

    for (short int count = 1; count <= 100; ++count) {

        int number = flip();

        if (number == 0) {
            printf("%s", "Tails");
            ++tails;
        }
        else if (number == 1) {
            printf_s("%s", "Heads");
            ++heads;
        }

    }//end for
    printf_s("\n%d Tails\n", tails);
    printf_s("%d Heads", heads);
}//end main

int flip(void) {

    srand(time(NULL));
    int number = (int)rand();
    printf("%d", number%2);
    return number%2;
}//end flip

I would run the program and my rand() value would always be a five digit integer repeated in each iteration of the for statement (i.e 15367, 15745, or 15943).

I messed around until I discovered changing srand(time(NULL)) to srand(time(NULL)*time(NULL)/rand()) did the trick.

My only thought is that the time between each for iteration is so small the the time(NULL) part of the srand() function doesn't change enough to feed a different seed value.

I also tried srand(time(NULL)/rand()), however, this produced the same result (52 heads 48 tails) every time I ran the program (20+times); however, the rand() values were all different from each other.

I do not know why these things happened, or why the final srand(time(NULL)*time(NULL)/rand()) function worked, and I would love it if someone could explain!


回答1:


The reason is, that time(NULL) changes only once per second! This means, that you seed the random number generator 100 times with the same seed. A better way is to seed the RNG only once at start of the process (at the head of main(), then you should get different values.

If you start your program more often than once a second, you could also seed it with

srand(time(NULL)+getpid());

or similar.



来源:https://stackoverflow.com/questions/52869281/why-does-my-srandtimenull-function-generate-the-same-number-every-time-in-c

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