C#Math.Ceiling将事件加倍...(500到501)(公式)

时间:2014-08-20 19:05:16

标签: c# excel math double ceil

为什么围绕C#计算这个计算?

500 - > 501

MessageBox.Show(Math.Ceiling(1 / (4 * 1 - 4 * 0.9) * 200).ToString());

返回。

---------------------------

---------------------------
501
---------------------------
OK   
---------------------------

我不知道为什么。

Excel也不会这样做。

Excel doesnt round the formula up.

我需要公式的天花板功能,它返回500而不是501。

我可以改用它。但我知道是否有另一种解决方案以及为什么C#会这样做。

MessageBox.Show(Math.Ceiling(Math.Floor((1 / (4 * 1 - 4 * 0.9) * 200) * 100) / 100).ToString());

1 个答案:

答案 0 :(得分:6)

问题在于500 实际上不是 500,而是由于使用浮点运算而导致500.0000000001(或类似的东西)。

要解决此问题,请使用decimal代替double

MessageBox.Show(Math.Ceiling(1.0M / (4.0M * 1.0M - 4.0M * 0.9M) * 200.0M).ToString());

有关详细信息,请参阅What every Computer Scientist should know about Floating-Point Arithmetic,或查看this网站以获得更简单的解释。