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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP