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
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.
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 torand()
. Ifsrand()
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
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,
You're missing the required header files. For rand()
and srand()
you need to have stdlib.h
, for time()
include time.h
.
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:
main()
is int main(void)
(in this case). return
value, though not mandatory in case of main()
.