C++ 隨機函數—-談rand() 和 srand() 體會

來源:互聯網
上載者:User

 在很多時候,程式中會用到隨機數,在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,,,,

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.