rand() is consistent across multiple function calls

后端 未结 2 1304
滥情空心
滥情空心 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.

    0 讨论(0)
  • 2021-01-15 04:20

    As per C11 standard document, chapter 7.22.2.2, srand() function,

    The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated.

    So, the issue with your code is you're calling srand( time(NULL) ); inside the test1() function. Effectively, you're seeding the pseudo-random number generator every time while calling the test() function. Now, the time(NULL) will return the same value for a whole second, i.e, it is having the time granularity of 1 second. So, successive calls to test() function within that granularity period (of 1 second) will cause

    • PRNG to be re-seeded with the same value
    • successive calls to rand() will produce the same set of random numbers.

    Solution: You need to call srand( time(NULL) ); only once from main().

    That said, two more important things to mention,

    1. You're missing the required header files. For rand() and srand() you need to have stdlib.h, for time() include time.h.

    2. Your int test1() function is declared to have a return value of type int, while your function does not have any return statement. It is acceptable if the returned value is not used in caller, but if in case the returned value is used, it will invoke undefined behavior. So better consider adding a return value in test() or change the return type to void.

    Sidenote:

    1. The recommended signature of main() is int main(void) (in this case).
    2. It is considered to be a good practice to add an explicit return value, though not mandatory in case of main().
    0 讨论(0)
提交回复
热议问题