歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> srand在隨機數發生器中的應用

srand在隨機數發生器中的應用

日期:2017/3/1 10:03:59   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved