有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?

Is there a way to produce random numbers simultaneously in c++? If not, is there a work around?

本文关键字:如果没有 随机数 是否 方法 解决 c++ 有没有      更新时间:2023-10-16
class Class{
int produceRandom(){
int ranNum = rand() % 5;
//other unrelated code
return ranNum;
}
std::vector<Class> classes;
int main(){
srand(time(NULL));
//codey code, unrelated
if (classes.empty() == false){
for (int i = 0; i < classes.size(); i++){
//Code produces a number of classes if certain conditions are met
int useRanNum = classes[i].produceRandom();
}
}
}

对于代码的每次迭代,这些数字足够随机,但每个类为每次迭代生成相同的数字。

我在这里遇到了一个完整的障碍,这让我发疯了。他们的解决方法吗?我做错了什么吗?我试过使用Mersenne Twister,但结果相同。任何帮助将不胜感激。

如果你使用随机库,你确实可以: https://en.cppreference.com/w/cpp/header/random

#include <random>
#include <iostream>
class Class{
private:
std::random_device rd;
std::mt19937 mt;
std::uniform_int_distribution<int> dist;
public:
Class() : rd(), mt(rd()), dist(0, 100) {}
int produceRandom() {
return dist(mt);
}
};
int main()
{
Class r;
for(int i = 0; i < 10; ++i)
{
std::cout << r.produceRandom() << 'n';
}
return 0;
}

两个可能的错误:

这一行:

for (int i; i < classes.size(); i++){

i未初始化。 因此,未定义的行为和/或始终奇怪的结果。 应该是:

for (int i = 0; i < classes.size(); i++){

另外,检查classes.empty() == false没有意义,更正的循环初始化将为您执行此操作。

但我的精神力量表明,代码中潜伏着另一种srand(N)调用,或者N是某个恒定值。 很可能在您尚未显示的代码部分和/或您正在调用的库中。

一种可能的解决方法是将srand(time(NULL))调用移动到"codey code,不相关"之后和循环之前。

那是:

int main(){
//codey code, unrelated

srand(time(NULL));  // move this line to be directly before the loop.
if (classes.empty() == false){
for (int i = 0; i < classes.size(); i++){
//Code produces a number of classes if certain conditions are met
int useRanNum = classes[i].produceRandom();
}
}
}
相关文章: