英文:
Random numbers are the same every time function is called
问题
以下是翻译好的部分:
"The numbers are random every time I run the program, but they stay the same during that same run. I want the numbers to be random every time the function is called.
I did seed the generator in main().
std::random_device device;
std::mt19937 generator(device());
My function
void takeAssignment(std::vector<Student> &students,
const int min, const int max,
std::mt19937 e)
{
std::uniform_int_distribution<int> dist(min, max);
// all students take the assignment
for (auto &s : students)
{
// random performance
int score{dist(e)};
s.addScore(score, max);
std::cout << s.getName() << "'s score: " << score << std::endl;
}
}
For example, everytime the function was called with the min as 0 and max as 10,
the output of the function printed
Abril Soto's score: 1
Bailey Case's score: 9
during that run.
Putting dist inside the loop didn't work either, the numbers stayed the same."
请注意,我已经将代码部分保持不变。
英文:
The numbers are random every time I run the program, but they stay the same during that same run. I want the numbers to be random every time the function is called.
I did seed the generator in main().
std::random_device device;
std::mt19937 generator(device());
My function
void takeAssignment(std::vector<Student> &students,
const int min, const int max,
std::mt19937 e)
{
std::uniform_int_distribution<int> dist(min, max);
// all students take the assignment
for (auto &s : students)
{
// random performance
int score{dist(e)};
s.addScore(score, max);
std::cout << s.getName() << "'s score: " << score << std::endl;
}
}
For example, everytime the function was called with the min as 0 and max as 10,
the output of the function printed
Abril Soto's score: 1
Bailey Case's score: 9
during that run.
Putting dist inside the loop didn't work either, the numbers stayed the same.
答案1
得分: 7
你通过按值传递生成器,从而创建一个没有种子并生成相同值的副本。尝试在函数参数中通过引用传递,例如:
std::mt19937& e
英文:
You're passing generator via call by value, thereby creating a copy with no seed and generating same values. Try passing by reference in function argument: like
std::mt19937& e
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论