使用 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

更新於: 30-Jul-2019

2K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.