第一种方法:使用时间做为生成随机数的种子
#include <iostream>
using namespace std;
// randomly generate 0 or 1
int main()
{
srand((unsigned)time(0));
for(int i = 0; i < 10; i++)
{
cout << rand() % 2 << "";
}
cout << endl << endl;
return 0;
}
第二种方法:使用C++提供的生成随机数的库函数
#include <iostream>
#include <random>
using namespace std;
// randomly generate 0 or 1
int main()
{
default_random_engine e(time(0));
uniform_int_distribution<unsigned>u(0,1);
for(int i = 0; i < 10; i++)
{
cout << u(e) << "";
}
cout << endl << endl;
return 0;
}
第三种方法参考Simple Random Number Generation
private static uint GetUint()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w;
}
public static double GetUniform()
{
// 0 <= u < 2^32
uint u = GetUint();
// The magic number below is 1/(2^32 + 2).
// The result is strictly between 0 and 1.
return (u + 1.0) * 2.328306435454494e-10;
}
m_z、m_w仅被初始化一次,GetUint函数返回无符号整数的随机数序列,GetUniform返回在(0,1)之间的随机浮点数,这个方法相比于以上两种方法的好处是上述两种方法,在不同的时刻产生的随机数序列不同,结果不可复现,而第三种方法产生的随机数序列始终相同,任意时刻运行程序的结果相同
注意事项:使用上述三种方法生成随机数序列时,种子只初始化一次,若重复初始化操作,则可能导致多次生成的随机数序列相同