使用C语言运行rand()并使用Shell脚本循环 [英] Run rand() in C language and loop with Shell Scripts

查看:229
本文介绍了使用C语言运行rand()并使用Shell脚本循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C代码文件(称为" test.c ",输出为" test.out "),如下所示,只是一个简单的随机数输出:

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;
}

现在,我使用外壳程序脚本在Linux中运行" test.out " 5次,以下代码:

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

但结果显示如下

0.840188
0.840188
0.840188
0.840188
0.840188

它显示相同的随机数.

推荐答案

您使用当前时间初始化伪随机数生成器.在大多数平台上,time函数以秒为单位返回当前时间 .如果您在一秒钟内多次运行该程序,那么您将在所有执行中设置相同的种子,并获得相同的随机"编号.

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.

添加例如脚本循环中的sleep 1,您将看到不同的结果.

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

这篇关于使用C语言运行rand()并使用Shell脚本循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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