硬件问题:我们将模拟掷骰子。再次,我们将使用Top-Down_Design来提高可读性,等等。
产生两个骰子的20个掷骰子。每个骰子可以生成1到6之间的点数。将两个数字相加即可得出掷出值。
一次生成20次抛出,并将数字存储在数组中。
第二遍计算这些数字的平均值,并将其显示在控制台上。
在获得任何随机数之前,先将8193种子植入随机数生成器。
注意:我们还没有讨论过将Array传递给函数。因此,对于此分配,您可以使Dice的数组全局抛出。
///我只是对将随机生成的数字添加到数组然后通过自顶向下方法进行平均的概念感到困惑。
#include <iostream>
#include <cstdlib>
using namespace std;
void Gen_20_Throws_Of_2_Die_And_Add_Values();
void Output_Avg(); //Calculates the average of the sum of the 20 rolls
int ArraySum[13]; // array for the numbers of 0-12 (13 total). Will ignore index array 0 and 1 later. array[13] = 12
int main()
{
Gen_20_Throws_Of_2_Die_And_Add_Values();
Output_Avg;
cin.get();
return 0;
}
void Gen_20_Throws_Of_2_Die_And_Add_Values()
{
srand(8193); //seed random number generator with 8193
int Dice_Throw_Number, Die1, Die2, Sum_Of_Two_Die;
for (int Dice_Throw_Number = 1; Dice_Throw_Number <= 20; Dice_Throw_Number++)
{
Die1 = (rand() % 6 + 1);
Die2 = (rand() % 6 + 1);
Sum_Of_Two_Die = Die1 + Die2;
ArraySum[Sum_Of_Two_Die] += 1;
}
}
void Output_Avg()
{
int Total_Of_20_Rolls, Average_Of_Rolls;
for (int i = 2; i <= 12; i++) //ignores index of 0 and 1
{
Total_Of_20_Rolls += ArraySum[i];
}
Average_Of_Rolls = Total_Of_20_Rolls / 20;
cout << "The average of 2 die rolled 20 times is " << Average_Of_Rolls;
}
答案 0 :(得分:0)
您的代码有些混乱,但是我想我了解发生了什么。让我们从您的Gen_20_Throws_Of_2_Die_And_Add_Values
方法开始。
int Dice_Throw_Number, Die1, Die2, Sum_Of_Two_Die;
for (int Dice_Throw_Number = 1; Dice_Throw_Number <= 20; Dice_Throw_Number++)
{
Die1 = (rand() % 6 + 1);
Die2 = (rand() % 6 + 1);
Sum_Of_Two_Die = Die1 + Die2;
ArraySum[Sum_Of_Two_Die] += 1;
}
您不必在for循环外初始化int Dice_Throw_Number
。随意将其放入for循环内。此外,我个人总是觉得从零开始直到仅达到<条件而不是<=更为容易理解。因此,您将拥有:
int Die1, Die2;
for (int Dice_Throw_Number = 0; Dice_Throw_Number < 20; Dice_Throw_Number++)
{
Die1 = (rand() % 6 + 1);
Die2 = (rand() % 6 + 1);
//increment position of sum by 1
ArraySum[Die1 + Die2] += 1;
}
现在,在您的Output_Average
函数中,您的逻辑有很多问题。您想计算两次掷骰子的平均结果是什么?现在,您只添加某个总数的出现次数,而不是总数本身。例如,如果您滚动12次5次,则将5添加到Total_Of_20_Rolls
中,而不是60。这很容易更改,只需乘以即可。
int Total_Of_20_Rolls, Average_Of_Rolls;
for (int i = 2; i < 13; i++) //ignores index of 0 and 1
{
Total_Of_20_Rolls += ArraySum[i] * i;
}
Average_Of_Rolls = Total_Of_20_Rolls / 20;
cout << "The average of 2 die rolled 20 times is " << Average_Of_Rolls;
那应该可以帮到你!