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

2014-11-24 08:47:22 ? 作者: ? 浏览: 1

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


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


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


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
#include
#include


using namespace std;


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


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


return 0;
}


-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: