I have a C code file (call \"test.c\" and output is \"test.out\") like below and just a simple output of random number:
int main()
{
You initialize the pseudorandom generator using the current time. On most platforms the time
function returns the current time in seconds. If you run this program multiple times in a single second then you will set the same seed in all executions, and get the same "random" number.
Add e.g. a sleep 1
in the loop in the script and you will see a different result.
for i in 1 2 3 4 5
do
test.out
done
You execute the program 5 times in the same second, and since you are using system time in seconds as seed for your rand()
function, naturally, you will get the same results. If you wait a second (or longer then a second) between executions, you will get different values.
rand()
will produce the same sequence of numbers for the same seed (the one you set with srand()
).
It's very likely that your loop runs too fast and all your runs end up using the same seed (i.e. time(NULL)
returns same value). Hence, you see the same output.
You can drand48()
instead for producing uniformly distributed numbers. Or if you simply want to test rand()
, you can just add a delay between your iterations.