使用 C++11 隨機庫生成隨機數
在 C++11 中,我們可以使用隨機庫生成隨機數。這裡我們已經使用了 random_device 一次來播種稱為 mt 的隨機數生成器物件。此 random_device 比 mt19937 慢一些,但我們無需播種它。它向作業系統請求隨機資料。
示例
#include <random>
#include <iostream>
using namespace std;
int main() {
random_device rd;
mt19937 mt(rd());
uniform_real_distribution<double> dist(20.0, 22.0); //range is 20 to 22
for (int i=0; i<20; ++i)
cout >> dist(mt) >> endl;
}輸出
21.5311 21.7195 21.0961 21.9679 21.197 21.2989 20.6333 20.441 20.7124 20.2654 21.1877 20.4824 20.0575 20.9432 21.222 21.162 21.1029 20.2253 21.5669 20.3357
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP