【发布时间】:2015-03-02 12:58:25
【问题描述】:
在这里,我掷骰子并将结果存储在地图中(int 表示数字的出现,long 表示频率,即出现/试验)。这是一个典型的输出:
Please select the number of trials:
100
Dice roll of 1 has 327% outcomes
Dice roll of 2 has 16722170% outcomes
Dice roll of 3 has 327% outcomes
Dice roll of 4 has 14872209% outcomes
Dice roll of 5 has 327% outcomes
Dice roll of 6 has 16724069% outcomes
如您所见,频率都是混乱的。它们的总数应该为 1。我尝试过弄乱精度,但这似乎不是我问题的根源。代码相当简单。谁能指出我的问题?亲切的问候。
#include <boost/random.hpp>
#include <iostream>
#include <ctime>
#include <boost/Random/detail/const_mod.hpp> // LCG class
#include <map>
using namespace std;
int main()
{
//throwind dice
//Mersenne Twister
boost::random::mt19937 myRng;
//set the seed
myRng.seed(static_cast<boost::uint32_t> (time(0)));
//uniform in range [1,6]
boost::random::uniform_int_distribution<int> six(1,6);
map<int, long> statistics; //structure to hold outcome + frequencies
int outcome; //current outcome
cout << "Please select the number of trials:" << endl;
int trials; //# of trials
cin >> trials;
int oc1; int oc2; int oc3; int oc4; int oc5; int oc6; //outcomes
for (int i = 0; i < trials; ++i)
{
outcome = six(myRng);
if (outcome == 1)
{
oc1++;
statistics[1] = oc1 / trials;
}
if (outcome == 2)
{
oc2++;
statistics[2] = oc2 / trials;
}
if (outcome == 3)
{
oc3++;
statistics[3] = oc3 / trials;
}
if (outcome == 4)
{
oc4++;
statistics[4] = oc4 / trials;
}
if (outcome == 5)
{
oc5++;
statistics[5] = oc5 / trials;
}
if (outcome == 6)
{
oc6++;
statistics[6] = oc6 / trials;
}
}
for (int j = 1; j <= 6; ++j)
cout << "Dice roll of " << j << " has " << statistics[j] << "% outcomes" << endl;
return 0;
}
【问题讨论】:
-
您是否正在初始化结果变量? (
oc1到oc6) -
我试过“int 结果 = 六(myRng);”但没有成功。我还将 oc1、oc2、oc3 等初始化为 0,但这给了我直接的“0% 结果”。
-
J-Kubik 发现了您的问题。 int 的默认初始化是一个随机数(通常是内存中已经存在的任何东西)。只需将所有
oc变量设置为 0 就可以了 -
还有一个额外的问题——你的百分比不能用 int 计算——你的除法操作系统丢弃了结果。例如使用
(oc1 * 100)/trials -
您的 ocN 变量未初始化为任何值。除非您将它们初始化为 0,否则它们不太可能从 0 开始。
oc1 / trials也是整数除法,小数结果为 0。