如何在 C++ 中生成一個隨機數?


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

要執行此操作,我們使用 srand() 函式。這在 C 庫中。函式 void srand(unsigned int seed) 為函式 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;
}

Output1

The random number is: 51

Output 2

The random number is: 29

Output 3

The random number is: 47

更新於:2019 年 7 月 30 日

391 次瀏覽

事業起飛

透過完成課程取得認證

開始
廣告