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