Dice roll not working C++ deafult_random_engine

2019-09-18 03:36发布

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;
}

2条回答
虎瘦雄心在
2楼-- · 2019-09-18 04:19
 #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;
 }
查看更多
爷的心禁止访问
3楼-- · 2019-09-18 04:25

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
查看更多
登录 后发表回答