我目前正在这个程序上掷2个骰子。但是,我的程序可以运行,由于某种原因,我对所有滚动总和的预期输出为0.000%,而不是预期值。我确定我正在忽略某些东西,但我不知道该怎么办。任何帮助深表感谢!
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
const int ROLLS = 36000;
const int SIZE = 13;
const int CW = 10;
// array 'expected' contains counts for the expected number of times
// each sum occurs in 36 rolls
int expected[SIZE]= {0,0,1/36,1/18,1/12,1/9,5/36,1/6,5/36,1/9,1/12,1/18,1/36};
int sum [SIZE] = {0};
int die1;
int die2;
srand(static_cast<unsigned>(time(nullptr)));
for (int i = 0; i <=ROLLS; ++i) {
die1 = 1 + rand() % 6;
die2 = 1 + rand() % 6;
sum[die1+die2]++;
}
cout << fixed << showpoint << setprecision(3);
cout << setw(CW) << "Sum" << setw(CW) << "Total"
<< setw(CW) << "Expected" << setw(CW) << "Actual" << endl;
for (int j = 2; j < SIZE; ++j) {
cout << setw(CW) << j << setw(CW) << sum[j]
<< setw(CW-1) << (100.0 * expected[j] / 36) << '%'
<< setw(CW-1) << (100.0 * sum[j] / ROLLS) << '%' << endl;
}
return 0;
}
答案 0 :(得分:4)
expected
的类型为int
,表示它是整数。您所有除法的结果都将被截断为最小整数,该整数始终为0。
您需要:
expected
声明为实数类型,例如float
或double
5.0f/36
或5.0/36
。