srand在随机数发生器中的应用

在C++中srand()与rand()都包含在头文件 <cstdlib> 中,下面首先看一个投六面骰子的随机数发生程序

/**********************************************************
        产生随机数发生器,范围1~6  产生20组数据
**********************************************************/
#include <iostream>
#include <iomanip> //setw()的头文件,setw()用来指定输出字符串宽度
#include <cstdlib>  
using namespace std;

int main()
{
    for(int i=1;i<=20;i++) //一共产生20组数据
    {
    cout<<setw(10)<<(1+rand()%6);
    if(i%5==0)  //每5个数据作为一行输出
    cout<<endl;
    }

    return 0;
}

其结果为:

6         6           5           5             6

5         1           1           5             3

6         6           2           4             2

6         2           3           4             1


但是多运行几次发现,上面每次的运行结果都一样。那是不是随机数不随机了呢?当然不是,当调试模拟程序时,对于证实程序的修改是否正确,这种重复性是至关重要的。

当调试完成后,可以设置条件使每次执行都产生不同的随机序列,这时就要用到srand()函数。srand函数是随机数发生器的初始化函数。

#include <iostream>
#include <cstdlib>
#include <iomanip>

using namespace std;

int main()
{
    unsigned int seed;
    cout<<"Enter seed: ";
    cin>>seed;
    srand(seed);

    for(int counter=1;counter<=10;counter++)
    {
        cout<<setw(10)<<(1+rand()%6);
        if(counter%5==0)
        cout<<endl;
    }

    return 0;
}

srand()为随机数发生器提供种子数即程序中的seed,当输入的种子值不同时,就会产生不同的随机数序列。

但每次都输入一个种子值,会使人感到很不方便,因此可以使用这样的语句    srand( time(0) ).

这会是计算机读取它的时钟值,以获得种子值。time(0)会返回系统的当前值,即从格林尼治统一时间(GMT)1970年1月1日 午夜开始到现在的秒数。这个值会转化成一个无符号整数值,并作为随机数生成器种子。time函数 包含在头文件<ctime> 中。

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>

using namespace std;

int main()
{
    srand(time(0));

    for(int counter=1;counter<=10;counter++)
    {
        cout<<setw(10)<<(1+rand()%6);
        if(counter%5==0)
        cout<<endl;
    }

    return 0;
}

本文系原创,转载请注明链接  http://blog.csdn.net/huangshizeng/article/details/6930879




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值