最近,我在C++中使用Mersenne-Twister算法生成随机数时遇到了一个问题。当迭代for循环并使用cout输出生成的数字时,它会重复输出相同的数字。例如,它输出类似于11 11 11而不是11 43 124的东西。我如何用代码来实现这一点?我现在的代码贴在下面。
#include <iostream>
#include <random>
#include <Windows.h>
#include <unistd.h>
using namespace std;
int main()
{
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(15000, 120000);
int random = dis(gen);
int i = 1;
while (i = 1) {
cout << random << endl;
}
return 0;任何帮助都是非常感谢的。
发布于 2018-01-31 23:20:12
random是一个整数对象。除非设置整数对象的值,否则其值不会更改。您在这里所做的类似于滚动模具,写下随机结果,然后反复阅读您所写的内容,期望书面结果发生变化。
通过在分布函数上多次应用生成器对象,可以生成多个随机数:
while (...)
cout << dis(gen) << endl;发布于 2018-02-01 00:41:30
您需要在循环中放置命令以获取随机数,否则只需反复打印相同的值:
int i = 1;
while (i = 1) {
int random = dis(gen); // get a new random number
cout << random << '\n'; // print it
}https://stackoverflow.com/questions/48552933
复制相似问题