在双值比较iOS中得到奇怪的结果

时间:2014-02-19 04:50:55

标签: ios objective-c comparison double

当我在if.. statement中比较双值时,我正在进行非常基本的计算并获得奇怪的结果。请参阅附件截图。 enter image description here

我用红色标记标记了变量值。您可以看到变量totalSliceValue的值为100,当我将值与100.0进行比较时,它会返回TRUE,但 100不会大于100 。< / p>

任何人都可以解释这个为什么我得到这个。我的代码中是否有任何错误,或者编译器存在问题。

提前致谢!

1 个答案:

答案 0 :(得分:1)

当它是双倍时,100通常大于100.或更少。它实际上是100.000000000127832645或类似的东西。

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Another of many articles on the problem developers face when working with floats and doubles.

解决方案:减去另一个双倍并检查结果是否太小以至于您可以将它们视为相等,而不是它们是相等的。

One duplicate StackOverflow question

Another duplicate

问题不在于编译器,而在于你指导它的方式 - 它是按照IEEE浮点规则工作的。