这个问题在这里已有答案:
我的代码处理两个骰子(10面“公平”骰子和20面“公平”骰子)并使用类,数组和随机数生成器生成两个骰子的随机卷及其求和,但我的所有代码都吐了out是“你滚动:18”。这不是很随机。
#include <iostream>
#include <stdlib.h>
using namespace std;
class Dice
{
private:
int rollDice[2] = {};
public:
void setval1(int x)
{
rollDice[0] = x;
}
void setval2(int y)
{
rollDice[1] = y;
}
double getVal1()
{
return rollDice[0];
}
double getVal2()
{
return rollDice[1];
}
};
int main()
{
Dice a;
a.setval1(rand()%9+1);
a.setval2(rand()%19+1);
cout << "You rolled: " << a.getVal1() + a.getVal2();
}
您需要为std :: rand()使用的伪随机数生成器播种。如果在对srand()的任何调用之前使用rand(),则rand()的行为就像是用srand(1)播种一样。
每次rand()用相同的种子播种时,它必须产生相同的值序列。
在C ++中正确使用将是这样的:
std::srand(std::time(nullptr)); // use current time as seed for random generator
int random_variable = std::rand();
如果你想要一个特定的统计分布,你应该看看标题随机documentation