【发布时间】:2019-10-31 04:03:00
【问题描述】:
我正在尝试创建一个程序,该程序将掷 2 个骰子 1000 万次,并输出每个数字掷了多少次。除此之外,我的任务是为输出创建直方图 (*=2000)。 这是我目前所拥有的。
/*
Creating a program that counts outcomes of two dice rolls, then show a
histogram of the outcomes.
Section 1 : Simulate ten million times rolls of two dice, while counting
outcomes. (Hint: Use an array of size 13.)
Section 2 : Show the outcome, the numbers of outcomes, and the histogram
(one * designates 20000). Your output must align properly.
*/
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
int i, j, ary[13] = {};
cout << "Please enter the random number seed.";
cin >> j;
srand(j);
for (i = 0; i < 10000000; i++)
ary[die() + die()]++;
for (i = 2; i <= 12; i++)
{
cout << setw(3) << i << " : " << setw(6) << ary[i] << " : ";
for (j = 0; j < ary[i]; j += 2000)
cout << "*";
cout << endl;
}
return 0;
}
示例输出:https://imgur.com/a/tETCj4O
我知道我需要用 rand() % 6 + 1;在程序的开头。我觉得我接近完成但缺少关键点!我也意识到我没有在 ary[]
中定义 die()【问题讨论】:
-
关于using namespace std...
-
忘记添加
die函数的定义了吗? -
rand()和模给出了相当糟糕的分布,更好的(假设没有发生溢出)是rand() * 6 / RAND_MAX。此外,我会考虑不为您的 die 值添加一个,而是在 [0 .. 5] 上进行操作。然后在输出时,您将迭代 [0 .. 10] 并将 2 添加到循环变量以再次获得 [2 .. 12] 。这样你就可以保护 999 988 个附加项...... -
有人可以帮我定义 die() 并插入一个 rand 函数