c++ - 数组的掷骰子

标签 c++ arrays

我需要这个程序做的是 roll 36000 2d6,以表格格式输出每个值的结果以及出现的频率。不幸的是,我不熟悉数组的工作原理。这是我目前所拥有的:

int DiceArray()
{
    int rollOne = 0;
    int rollTwo = 0;
    int countrolls = 0;
    int sum = 0;
    for (countrolls=1; countrolls<=36000; countrolls++)
    {
        rollOne = (rand() % 6) + 1;
        rollTwo = (rand() % 6) + 1;
        sum = rollOne+rollTwo;
    }
}

所以,我需要一个骰子结果数组,我猜它看起来像 result[11],因为它列出了 2 到 12 的骰子总和。然后我将不得不使数组多维;我需要第二列来显示结果。

因此,例如,2 的结果会出现 700 次。所以我需要类似 outcome[2] 的东西。是对的吗?无论如何,我如何为我的数组获得正确的值?

我想对于结果数组我只是像这样列出它们因为它们总是相同的:{2, 3, 4,... 12}

但是如何将总和输出到数组?

最佳答案

不确定,你在问什么,但看起来你需要一个简单的 histogram .像这样:

void DiceArray()
{
  int rollOne = 0;
  int rollTwo = 0;
  int sum = 0;

  // This array holds histogram. hist[0] and hist[1] are always zero.
  int hist[13] = { 0 }; 

  for (int countrolls = 0; countrolls < 36000; ++countrolls)
  {
    rollOne = (rand() % 6) + 1;
    rollTwo = (rand() % 6) + 1;
    sum = rollOne+rollTwo;
    hist[sum]++;
  }

  for (int i = 2; i <= 12; ++i)
  {
    std::cout << i << ": " << hist[i] << std::endl;
  }
}

此函数打印以下内容:

2: 949
3: 1974
4: 2898
5: 3987
6: 5133
7: 6088
8: 4944
9: 3976
10: 3075
11: 1991
12: 985

关于c++ - 数组的掷骰子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22207003/

相关文章:

c++ - 无法在 Release 模式下在 Qt 中加载 QSQLCIPHER

c++ - “struct _ntl_gbigint_body”在哪里定义?

c++ - 在 Netbeans 中调试 C++

arrays - 如何将具有重复键的散列数组 "reduce"嵌套散列?

Java在列表末尾添加

javascript - 如何使用angularjs在html中打印数组对象数组

c++ - 如何在wxWidgets中刷新,C++

c++ - 将 CString 转换为 const char*

arrays - 如何从数组制作图形?

c - 在基本c程序中查找重复时输出错误0