C++ 中的隨機數生成


下面我們看一下如何使用 C++ 來生成隨機數。在這裡,我們在範圍 0 到某個值內生成隨機數。(在這個程式中,最大值為 100)。

為了執行此操作,我們使用了 srand() 函式。這個函式在 C 庫中。函式 void srand(無符號整數種子)對函式 rand 使用的隨機數生成器設定種子。

srand() 的宣告如下

void srand(unsigned int seed)

它接收一個稱為 種子的引數。這是由偽隨機數生成器演算法用作種子的整數值。此函式不返回值。

為了獲取數字,我們需要 rand() 方法。為了在 0 到最大值範圍內獲取數字,我們使用模運算子來獲取餘數。

對於種子值,我們正在將 time(0) 函式結果提供給 srand() 函式。

示例程式碼

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
main() {
   int max;
   max = 100; //set the upper bound to generate the random number
   srand(time(0));
   cout << "The random number is: "<<rand()%max;
}

輸出 1

The random number is: 51

輸出 2

The random number is: 29

輸出 3

The random number is: 47

更新日期:2019 年 7 月 30 日

213 次瀏覽

開啟您的 職業生涯

完成課程以取得認證

開始
廣告