【发布时间】:2018-10-21 05:22:39
【问题描述】:
硬件问题:我们将模拟掷骰子。我们将再次使用 Top-Down_Design 来提高可读性等。
产生 20 次掷骰子的两个骰子。每个骰子可以产生从 1 到 6 的点数。将两个数字相加得到掷出的点数。
一次性生成 20 次掷球并将数字存储在一个数组中。
在第二遍中计算数字的平均值并将其显示在控制台上。
在获得任何随机数之前,使用 8193 播种一次随机数生成器。
注意:我们还没有讨论将数组传递给函数。因此,对于这个任务,您可以将 Dice throws 数组设为全局。
//我只是对将随机生成的数字添加到数组中然后通过自上而下方法对其进行平均的概念感到困惑。
#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;
}
【问题讨论】: