使用float时为什么会得到错误的结果?

可能重复:
为什么(双)0.6f>(双)(6 / 10f)?
为什么C#中的浮点运算不精确?

我在C#中有以下代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StackOverflow { class Program { static void Main(string[] args) { float num1 = 17.03F; float num2 = 17F; float result = num1 - num2; Console.WriteLine(result); } } } 

代码工作正常,但我没有得到预期的结果。 有人可以解释为什么会这样吗?

我猜你是指浮点算术引起的偏差。 您可以在提供的链接中阅读。

如果您确实需要使计算100%准确,则可以使用decimal而不是float

因为你正在使用float 。 Float是一个非常接近的值。 比较时,请始终使用Epsilon(最大误差容差)。

我猜你得到的结果= 0.02999999?

浮点数学可能包含舍入近似值,请参阅本网站上的许多重复问题,或在此处阅读:

http://en.wikipedia.org/wiki/Floating_point

那这个呢? : 每个计算机科学家应该知道的浮点运算