为什么 rand() 每次运行都会产生相同的数字序列?

2024-04-08

每次我运行一个程序时rand()它给了我同样的结果。

Example:

#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;
}

Output:

3
5
4
2
3

每次我运行该程序时,它每次都会输出相同的数字。有没有解决的办法?


未设置随机数生成器的种子。

如果你打电话srand((unsigned int)time(NULL))那么你会得到更多的随机结果:

#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具有真正的随机数),那么您将始终得到相同的“随机”数。

如果您想了解更多,可以阅读以下内容:

http://www.dreamincode.net/forums/topic/24225-random-number- Generation-102/ 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/ http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 rand() 每次运行都会产生相同的数字序列? 的相关文章

随机推荐