Run rand() in C language and loop with Shell Scrip

2020-02-07 12:55发布

问题:

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()
{
    srand(time(NULL)); 
    double r = (double)rand() / (double)RAND_MAX;
    printf("%f\n", r);
    return 0;
}

and now I use shell scripts to run "test.out" 5 times in Linux, the code below:

for i in 1 2 3 4 5
do
    test.out
done

but the result show like below

0.840188
0.840188
0.840188
0.840188
0.840188

It shows the same random number.

回答1:

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.



回答2:

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.



回答3:

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.



标签: c shell random