C++11增加了产生随机数的引擎类,可以更方便的产生随机数:
#include <iostream>
#include <chrono>
#include <random>
using namespace std;
unsigned long getRand()
{
static default_random_engine e(chrono::system_clock::now().time_since_epoch().count()/chrono::system_clock::period::den);
return e();
}
int main()
{
for(int i=0; i<10; i++)
{
cout << getRand() << endl;
}
return 0;
}
运行程序输出:
887311763
922355973
1499874165
1222042669
337537975
1496434098
1386895069
757920145
1638366658
993099172
需要注意的是如果getRand中,不把e定义为静态变量,那么getRand将输出相同的数值:
#include <iostream>
#include <chrono>