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

来源:互联网 发布:java编写图书馆系统 编辑:程序博客网 时间:2024/05/26 19:15

在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




原创粉丝点击