随机数在每次函数调用时都相同。

huangapple go评论70阅读模式
英文:

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&lt;Student&gt; &amp;students,
                    const int min, const int max,
                    std::mt19937 e)
{
    std::uniform_int_distribution&lt;int&gt; dist(min, max);
    // all students take the assignment
    for (auto &amp;s : students)
    {
        // random performance
        int score{dist(e)};
        s.addScore(score, max);
        std::cout &lt;&lt; s.getName() &lt;&lt; &quot;&#39;s score: &quot; &lt;&lt; score &lt;&lt; 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&#39;s score: 1
Bailey Case&#39;s score: 9

during that run.

Putting dist inside the loop didn't work either, the numbers stayed the same.

答案1

得分: 7

你通过按值传递生成器,从而创建一个没有种子并生成相同值的副本。尝试在函数参数中通过引用传递,例如:

std::mt19937&amp; 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&amp; e

huangapple
  • 本文由 发表于 2020年1月3日 19:04:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577450.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定