首页 > 解决方案 > 将随机生成的数字添加到数组 + 平均这些数组

问题描述

硬件问题:我们将模拟掷骰子。我们将再次使用 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;
}

标签: c++arraysdice

解决方案


您的代码有点令人困惑,但我想我明白发生了什么。让我们从你的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;

那应该可以帮助你!


推荐阅读