rand() is consistent across multiple function calls

后端 未结 2 1305
滥情空心
滥情空心 2021-01-15 04:07

When I try to generate 2 random numbers from within a function call, I\'m getting repeated results.

However, the rand() function works fine in loops or

2条回答
  •  走了就别回头了
    2021-01-15 04:08

    It is because you call

    srand( time(NULL) );
    

    every time you use the function. Its granularity is one second, so If you call it twice within a very short time interval, you will seed the random number generator with the same value - unless the clock happens to tick just between the two calls.

    You should call srand() once at the start of your program.

提交回复
热议问题