C 隨機函式

2021-12-30 05:35:32 字數 943 閱讀 6897

在很多時候,程式中會用到隨機數,在c++中就要用到專門用以產生隨機數的標準庫函式rand(),它會產生乙個無符號整數,範圍在0~32767,即兩位元組16位的整數最大值。而gnu c++產生的隨機數範圍為2147483647。 範圍中的每乙個數在每次隨機呼叫rand時都有相同的概率被選中。

呼叫時 ,需要引用標頭檔案,示例**

//擲20次篩子,每五個一行輸出

#include "stdafx.h"

#include

using std::cout;

using std::endl;

#include

using std::setw ;

#include

using std::rand;

int _tmain(int argc, _tchar* ar**)

}return 0;

}  當我們多次執行後,我們會發現每次執行的結果是一樣的,既然是隨機,這是為什麼呢???

這是因為,rand()產生的實際上是乙個偽隨機數,如果要確保每次產生的都不一樣,我們需要引用乙個專門為rand設定隨機化種子的函式srand().示例**如下:

#include "stdafx.h"

#include

using std::cout;

using std::endl;

using std::cin ;

#include

using std::setw ;

#include

using std::rand;

using std::srand;

int _tmain(int argc, _tchar* ar**)

}return 0;

}結果1種子為:67

2種子為76

3當再次執行後,種子仍然為76的時候,結果和上次執行的一樣:

ok,,,,

C 隨機函式

1.srand 和 rand 函式 rand 產生隨機數,一般是從srand seed 中指定的seed開始,返回乙個 seed,rand max 0x7fff 間的隨機整數。如果使用者在此之前沒有呼叫過srand seed 它會自動呼叫srand 1 一次。如果seed的值每次都一樣,那麼產生的隨...

C 隨機函式(VC program)

c 隨機函式 vc program include include include using namespace std define max 100 int main int argc,char argv srand unsigned time null srand 函式產生乙個以當前時間開始的...

c語言 隨機函式

c語言 隨機函式 include rand srand 標準c庫中函式rand 可以生成0 rand max 之間的乙個隨機數,其中rand max 是stdlib.h 中定義的乙個整數,它與系統有關。rand 函式沒有輸入引數,直接通過表示式rand 來引用 例如可以用下面的語句來列印兩個隨機數 ...