在很多時候,程式中會用到隨機數,在C++中就要用到專門用以產生隨機數的標準庫函數rand(),它會產生一個不帶正負號的整數,範圍在0~32767,即兩位元組16位的整數最大值。而GNU C++產生的隨機數範圍為2147483647。 範圍中的每一個數在每次隨機調用rand時都有相同的機率被選中。
調用時 ,需要引用標頭檔<cstdlib>,範例程式碼
//擲20次篩子,每五個一行輸出
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw ;
#include <cstdlib>
using std::rand;
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=1;i<=20;i++)
{
cout<<setw(10)<<(1+rand()%6);//比例縮放,6稱為縮放因子
if(i%5==0)
{
cout<<endl;
}
}
return 0;
}
當我們多次執行後,我們會發現每次執行的結果是一樣的,既然是隨機,這是為什麼呢???
這是因為,rand()產生的實際上是一個偽隨機數,如果要確保每次產生的都不一樣,我們需要引用一個專門為rand設定隨機化種子的函數srand().範例程式碼如下:
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin ;
#include <iomanip>
using std::setw ;
#include <cstdlib>
using std::rand;
using std::srand;
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int seed;
cout<<"輸入隨機化種子(它是一個不帶正負號的整數)";
cin>>seed;
srand(seed);
for(int i=1;i<=20;i++)
{
cout<<setw(10)<<(1+rand()%6);//比例縮放,6稱為縮放因子
if(i%5==0)
{
cout<<endl;
}
}
return 0;
}
結果1種子為:67
2種子為76
3當再次執行後,種子仍然為76的時候,結果和上次執行的一樣:
OK,,,,