2014-09-19 179 views
0

我无法正确输出此程序。它模拟一个醉酒的水手,随机向左或向右走一步。在模拟结束时,程序输出他掉到板上的时间百分比而不是下降。我的百分比总是为零,我无法弄清楚我的代码有什么问题。输出功能故障C++

该函数正确输出“实验”和“fallCount”变量,但始终显示“fallCount/experiments”为零。

这应该是:“经过2次实验,水手下降1次,下降百分比为0.5%” (如果实验= 2且fallCount = 1),则其每次为0%。

让我知道我做错了什么。谢谢!

void outputExperimentStats(int experiments, int fallCount) 
{ 
cout << "After " << experiments << " experiments, sailor fell " 
<< fallCount << " time, fall percentage was " << fallCount/experiments << "%\n"; 
} 

回答

1

那是因为你正在使用整数除法。没有小数,所以事情被截断。例如。

1/2 --> 0 // integer division 

这是正确的,和预期的行为。

要获得您想要的行为,请使用doublefloat

1.0/2.0 --> 0.5 // double division 

在你的榜样,你可以改变类型的输入double或者,如果你想保持他们int,可以划分

static_cast<double>(fallCount)/static_cast<double>(experiments) 
+0

非常感谢你在它们转换!它完美的作品。 – 2014-09-19 16:56:09