运行兰特()的C语言和循环与壳牌Scirpts [英] Run rand() in C language and loop with Shell Scirpts

查看:165
本文介绍了运行兰特()的C语言和循环与壳牌Scirpts的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直停留在一个问题。
我有一个C code文件(称为 test.c的的,并输出 test.out 的)像下面和随机数的只是一个简单的输出:结果

Recently I had been stuck on a question. 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;
}

现在我使用shell脚本运行的 test.out 的Linux中的5次,code如下:

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...
Can anyone have any suggestion?

太感谢了!

推荐答案

您使用初始化当前时间的伪随机数生成。在大多数平台上的时间函数返回以秒为当前时间的 的。如果在一分一秒多次运行这个程序,那么你将设置所有执行相同的种子,并获得相同的随机数。

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.

添加例如一个睡1 在脚本中的循环,你会看到一个不同的结果。

Add e.g. a sleep 1 in the loop in the script and you will see a different result.

这篇关于运行兰特()的C语言和循环与壳牌Scirpts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆