我有以下生成随机数的方法:
int random_number() //Random number generator
{
int x = rand() % 1000000 + 1; //Generate an integer between 1 and 1000000
return x;
}
对这个方法的调用是在一个迭代五次的循环中使用的。这种方法的问题在于,多次运行程序时,它似乎总是生成相同的数字。如何解决?
最佳答案
您需要 seed随机数生成器,例如:
srand ( time(NULL) );
int x = rand() % 1000000 + 1;
为伪随机数生成器播种基本上决定了它将遍历的随机数集。使用时间是获得充分随机结果的标准方法。
编辑:
澄清一下,您应该只播种一次并获得许多随机数,如下所示:
srand ( time(NULL) );
loop {
int x = rand() % 1000000 + 1;
}
而不是像这样的东西:
loop {
//Particularly bad if this line is hit multiple times in one second
srand ( time(NULL) );
int x = rand() % 1000000 + 1;
}
关于c++ - rand() 总是在应用程序重启时返回相同的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13274338/