c++ - 将随机生成的数字添加到数组 + 平均这些数组
问题描述
硬件问题:我们将模拟掷骰子。我们将再次使用 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;
}
解决方案
您的代码有点令人困惑,但我想我明白发生了什么。让我们从你的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;
}
您不必int Dice_Throw_Number
在 for 循环之外进行初始化。随意将其放入 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
函数中,你的逻辑大错特错了。您想计算掷 2 颗骰子的平均结果是多少?现在,您只是添加某个总数出现的次数,而不是总数本身。因此,例如,如果您将 12 掷了 5 次,您将在 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;
那应该可以帮助你!
推荐阅读
- php - 尽管 phpinfo() 和 php -m 将其显示为已启用,但 XMLWriter 无法正常工作
- css - 如何使文本填充由具有负左边距的图像(旁边)创建的空白?
- php - 根据在 WooCommerce 中购买的产品更改用户角色
- android - Android:如何访问显示应用内容的缺口区域?
- opengl - 二维坐标混淆
- haskell - 当数据构造函数不在范围内时,如何对抽象数据类型进行模式匹配?
- r - 不能在 dplyr 中使用多字变量还是我遗漏了什么?
- javascript - 如何使用 three.js 围绕其轴旋转网格?
- javascript - 如何从给定的 RegEx 中删除分隔符?
- android - 如何从 RecyclerView 的一行中打开摄像头并在 onActivityResult 中返回结果?