有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
Is there a way to produce random numbers simultaneously in c++? If not, is there a work around?
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();
}
}
}
相关文章:
- 如果没有malloc,链表实现将失败
- 如果没有数学库,我如何在C++中创建复利公式
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 为什么使用 std::vector 的代码不能编译,但使用 std::unique_ptr 如果没有 noexcept
- 如果没有重新散列,为什么 unordered_set::begin() 会改变?
- 包装器是从 strcat_s() 到 strcat() 吗?如果没有,是否可以创建一个?
- 检查私有成员变量是否在一定范围内,如果没有调整
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 编译了一个recent-C++.因此,如果没有暴露std符号,请在旧系统上运行
- 是否可以"unprivate" C++继承中的元素?如果没有怎么办?
- 在C++中加载火炬脚本模型:如果没有ATen_cuda库,则无法初始化 CUDA
- 如果没有 #pragma pop_macro #pragma push_macro 会发生什么?
- 在不放置新运算符的情况下,在预分配的内存上使用虚函数初始化对象 - 这可能吗?如果没有,为什么
- 如果没有带有函数签名的 rvalue 参数,是否会执行 C++ 11 中的移动语义?
- 如果没有指针,如何识别堆栈上的内存?
- 如果没有未定义的行为 [c++],哪些浮点值无法转换为 int?
- 如果没有'&&'语句有效?
- 拥有 std::map 的最佳方式,我可以在其中定义如果没有键时返回的内容
- 如果没有数据,则创建一个包含数据的文本文件,然后读取它以检索数据