随机数生成器为一个或两个骰子

random number generator for one or two dice

本文关键字:两个 随机数生成器 一个      更新时间:2023-10-16

这个头文件创建了一个大小取决于骰子数量的矢量。它包含投掷次数(rollsN),骰子数量(numDice)和骰子的面数(numSides—固定为6)。我认为问题出在第一个for循环中。当设置为一个骰子时,它将按预期运行,但当应用两个骰子时,它将以超出范围错误终止。

void randomNum(const int rollsN, int numDice, int numSides)
{
//Vector will hold an extra value (starts at 0, not 1). 
vector<int> numVect((numDice*numSides) + 1);
//Starts a randomizer based on time
srand(time(0));
//provides random values for every possible result of the die
for(int i = 0; i < rollsN; i++)
{
    int temp = 0; //holds the side of the dice that is chosen... or the sum of the two dice that are rolled
    for(int j = 0; j < numDice; j++)
    {
        temp += (rand() % (numDice*numSides) + 1); 
    }
    numVect.at(temp) += 1;
}
//prints how many times the die landed on that value
cout << endl << "RANDOMIZED RESULTS " << endl;
for(int i = 1; i <= (numDice*numSides); i++)
{
    cout << i << " ----- " << numVect[i] << endl;
}
cout << "~~~~~~~~~~~~~~~~~~~~~~~" << endl << "Histogram" << endl;

}

此代码

for(int j = 0; j < numDice; j++)
{
    temp += (rand() % (numDice*numSides) + 1); 
}

每个随机数从1到numDice*numSides。您正在将这个numDice添加几次,导致numDice*numDice*numSides的潜在最大数量超出了您的范围。

改为:

for(int j = 0; j < numDice; j++)
{
    temp += rand() % numSides + 1; 
}