出于某种原因,我每次都会得到6
。我知道另一种做随机骰子的方法,但我想学习如何使用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;
}
但是这段代码适用于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;
}
答案 0 :(得分:0)
几乎可以肯定,time(0)
是罪魁祸首。
你应该选择这样的方法:
#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;
}
虽然您的原始代码始终在我的系统上生成6
,但这个代码似乎更“冒险”:
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
答案 1 :(得分:0)
#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;
}