【发布时间】:2015-07-19 05:49:05
【问题描述】:
我有一个 C++ 作业要做,这就是问题
//Dietel & Dietel C Programming //Chapter 6 Arrays: Page 241 Exercise:
6.19 /* Write a program that simulates the rolling of two dice.
* The program should use rand to roll the first die, and
* should use rand again to roll the second die.
* The sum of the two values should then be calculated. (Note: Since each die
* can show an integer value from 1 to 6, then the sum of the two values will vary
* from 2 to 12 with 7 being the most freqent sum and 2 and 12 being the least frequent
* sums.) Figure 6.23 shows the 36 possible combinations of the two dice.
* Your program should
* roll the two dice 36,000 times. Use a single-scripted array to tally the numbers of times
* each possible sum appears.
* Print the results in a tabular format. Also, determine if the totals
* are resonable; i.e there are six ways to roll a 7, so approximately one sixth of all of the
* rolls should be 7.
*/
我创建了程序,但它给了我这样的输出:
sum of Faces Frequency
2 0
3 4041
4 0
5 7922
6 0
7 12154
8 0
9 7936
10 0
11 3948
12 0
sum: 36001
我不明白为什么它给所有偶数的频率都设为 0
这是我目前编写的代码:
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
const int arraysize = 13;
int counter[13], sum=0;
// init counter
for(int i=0; i<13; i++)
counter[i] = 0;
int die1;
int die2;
for ( int roll1 = 0; roll1 <=36000; roll1++ ) {
die1 = 1 + rand() % 6;
die2 = 1 + rand() % 6;
counter[die1+die2]++;
}
cout<<"sum of Faces"<<setw(13)<<"Frequency"<<endl;
for(int face=2; face<arraysize;face++)
{
cout<<setw(7)<<face<<setw(13)<<counter[face]<<endl;
sum += counter[face];
}
cout << "sum: " << sum;
return 0;
}
我还需要为骰子添加可能性,例如:
1 + 1 = 2 : 1 possibility for sum to be 2
1 + 2 = 2 + 1 = 3 : 2 possibility for sum to be 3
1 + 3 = 2 + 2 = 3 + 1 = 4 : 3 possibility for sum to be 4
.
.
.
6 + 6 = 12 : 1 possibility for sum to be 12
【问题讨论】:
-
又来了一个作业,让我们这样做吧!! :D
-
I don't why it's giving 0 frequency for all even numbers为什么不呢?你写程序了吗?如果您这样做了,请调试您的程序以找出偶数不正确运行的原因。 -
看起来您对
rand的实现可能很差。尝试改用现代的<random>库。 -
如果您没有复制并粘贴该代码而是重新输入了它,我会寻找一个错字,其中
die1意外变为die2,反之亦然。 -
@moose 你可以很容易地成为你自己的侦探。只需通过添加两个简单的
cout行(最基本的调试技术——输出值)来输出您正在使用的值。如果您只是简单地输出die1和die2的值,那么您会将问题集中在rand()函数无法正常工作上。那么你的问题可能是my rand() function is not working correctly when I do this...而不是I don't know what's wrong with my program。