如何在 C++ 中迴圈生成不同的隨機數?


讓我們看看如何使用 C++ 生成不同的隨機數。此處我們生成範圍 0 到某個值的隨機數。(此程式中的最大值為 100)。

要執行此操作,我們使用 srand() 函式。該函式在 C++ 庫中。該函式 void srand(unsigned int seed) 生成由函式 rand 使用的隨機數生成器。用種子。

srand() 的宣告如下 -

void srand(unsigned int seed)

它帶有一個名為種子的引數。這是一個整數值,將被偽隨機數生成器演算法用作種子。此函式不返回任何內容。

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

對於種子值我們向 srand() 函式提供 time(0) 函式結果。

示例

#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));
   for(int i = 0; i<10; i++) { //generate 10 random numbers
      cout << "The random number is: "<<rand()%max << endl;
   }
}

輸出

The random number is: 6
The random number is: 82
The random number is: 51
The random number is: 46
The random number is: 97
The random number is: 60
The random number is: 20
The random number is: 2
The random number is: 55
The random number is: 91

更新於: 2019 年 7 月 30 日

4K+ 瀏覽量

開啟您的 職業生涯

透過完成該課程獲得認證

開始學習
廣告