C++ 程式生成隨機數


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

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

srand() 的宣告如下

void srand(unsigned int seed)

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

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

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

示例程式碼

#include<iostream>
#include<cstdlib>
#include
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 日

4K+ 瀏覽次數

開啟你的 職業之旅

完成課程獲得認證

開始
廣告
© . All rights reserved.