问题描述
每次我使用rand()
运行程序时,都会得到相同的结果.
Every time I run a program with rand()
it gives me the same results.
示例:
#include <iostream>
#include <cstdlib>
using namespace std;
int random (int low, int high) {
if (low > high)
return high;
return low + (rand() % (high - low + 1));
}
int main (int argc, char* argv []) {
for (int i = 0; i < 5; i++)
cout << random (2, 5) << endl;
}
输出:
3
5
4
2
3
每次运行程序时,每次输出相同的数字.有办法解决吗?
Each time I run the program it outputs the same numbers every time. Is there a way around this?
推荐答案
未设置随机数生成器的种子.
The seed for the random number generator is not set.
如果您致电srand((unsigned int)time(NULL))
,您将获得更多随机结果:
If you call srand((unsigned int)time(NULL))
then you will get more random results:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand((unsigned int)time(NULL));
cout << rand() << endl;
return 0;
}
原因是从rand()
函数生成的随机数实际上不是随机数.这只是一个转变.维基百科更好地解释了伪随机数生成器的含义:确定性随机位生成器.每次调用rand()
时,它都会获取生成的种子和/或最后一个随机数(C标准未指定所使用的算法,尽管C ++ 11具有指定某些流行算法的功能),对这些数字进行数学运算,并返回结果.因此,如果每次的种子状态都是相同的(例如,如果您不使用真正的随机数调用srand
),那么您总是会得到相同的随机"数.
The reason is that a random number generated from the rand()
function isn't actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand()
it takes the seed and/or the last random number(s) generated (the C standard doesn't specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don't call srand
with a truly random number), then you will always get the same 'random' numbers out.
如果您想了解更多信息,可以阅读以下内容:
If you want to know more, you can read the following:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/
这篇关于为什么rand()每次运行都会产生相同的数字序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!