Dice roll not working C++ deafult_random_engine

隐身守侯 提交于 2019-12-12 05:56:42

问题


For some reason I keep getting 6 every time. I know of another way to do a random dice roll, but I wanted to learn how to use the deafult_random_engine.

#include <iostream>
#include <string>
#include <random>
#include <ctime>

using namespace std;

int main()
{
    default_random_engine randomGenerator(time(0));
    uniform_int_distribution<int> diceRoll(1, 6);

    cout << "You rolled a " << diceRoll(randomGenerator) << endl;
}

But this bit of code works with the time(0).

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
// dice roll
{
    srand(time(0));
    for(int x = 1; x < 2; x++){
        cout << 1+(rand()%6) << endl;
    }
    return 0;
}

回答1:


It's almost certainly the use of time(0) as the culprit here.

You should probably opt for a method like this:

#include <iostream>
#include <string>
#include <chrono>
#include <random>
#include <ctime>

using namespace std;

int main() {
    default_random_engine randomGenerator(std::random_device{}());
    // OR:
    // default_random_engine randomGenerator(
    //  (unsigned) chrono::system_clock::now().time_since_epoch().count());

    uniform_int_distribution<int> diceRoll(1, 6);

    cout << "You rolled a " << diceRoll(randomGenerator) << endl;

    return 0;
}

While your original code always produced 6 on my system, this one seems a little more "adventurous":

pax> for i in {1..10}; do ./qq ; sleep 1 ; done
You rolled a 5
You rolled a 5
You rolled a 6
You rolled a 1
You rolled a 6
You rolled a 5
You rolled a 2
You rolled a 3
You rolled a 5
You rolled a 4



回答2:


 #include <iostream>
 #include <string>
 #include <random>
 #include <ctime>

 using namespace std;

 int main()
 {
  mt19937 randomGenerator(time(0));
  uniform_int_distribution<int> diceRoll(1, 6);

  cout << "You rolled a " << diceRoll(randomGenerator) << endl;
 }


来源:https://stackoverflow.com/questions/28733622/dice-roll-not-working-c-deafult-random-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!