[英]Arithmetic operation gives incorrect result
I might be missing something very basic here. 我可能在这里错过了一些非常基本的东西。 But I don't know how to figure out that basic thing.
但是我不知道该怎么办。 When I set T to 10 and dt to 0.1, I should get the result 101 but I am getting the result as 100. Why is it so?
当我将T设置为10并将dt设置为0.1时,我应该得到结果101,但我得到的结果是100。为什么会这样?
n_sim_steps = (int)(T/dt) + 1
Furthermore, if I execute this as a watch in eclipse, it returns 101, but in code it results in 100. 此外,如果我将其作为日食手表执行,则返回101,但在代码中返回100。
It should be 它应该是
n_sim_steps = (int)(T/dt + 0.5) + 1
You are a victim of precission loss 您是失去精确性的受害者
10 / 0.1
may be 99.999999999999
because of this loss and may be casted back to int
as 99
. 由于此损失,
10 / 0.1
可能是99.999999999999
,并且可能会被强制转换回int
为99
。 Adding 0.5
and then casting would make sure that the result is rounded. 添加
0.5
,然后进行强制转换将确保结果是四舍五入的。
You better to use ceil function. 您最好使用ceil函数。
function signature 功能签名
double ceil (double x);
like ceil(2.3) will results 3 像ceil(2.3)会得到3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.