我需要这个程序做的是 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/