用于一个或两个骰子的随机数发生器

时间:2015-10-19 01:34:06

标签: c++ random vector stdvector

此头文件创建一个大小取决于骰子数量的向量。它需要卷数(掷骰N),骰子数(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;

}

1 个答案:

答案 0 :(得分:1)

此代码

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