比较浮点在目标C中的奇怪问题 [英] Strange problem comparing floats in objective-C
问题描述
在算法的某个时候,我需要比较一个类的属性的float值为float。所以我这样做:
At some point in an algorithm I need to compare the float value of a property of a class to a float. So I do this:
if (self.scroller.currentValue <= 0.1) {
}
其中currentValue是一个float属性。
where currentValue is a float property.
当我有相等和 self.scroller.currentValue = 0.1
if语句未被满足,代码未执行!我发现,我可以通过转换0.1来解决这个问题。像这样:
However, when I have equality and self.scroller.currentValue = 0.1
the if statement is not fulfilled and the code not executed! I found out that I can fix this by casting 0.1 to float. Like this:
if (self.scroller.currentValue <= (float)0.1) {
}
这很好。
我为什么会发生这种情况?
Can anyone explain to my why this is happening? Is 0.1 defined as a double by default or something?
推荐答案
我相信,没有找到这样的标准,当比较 float
到 double
float
在比较前转换为 double
。没有修饰符的浮点数在C中被认为是 double
I believe, having not found the standard that says so, that when comparing a float
to a double
the float
is cast to a double
before comparing. Floating point numbers without a modifier are considered to be double
in C.
然而,在C中没有精确0.1的浮点和双精度表示。现在,使用一个float给你一个小错误。使用double会给你一个更小的错误。现在的问题是,通过将 float
转换为 double
c $ c> float 。
However, in C there is no exact representation of 0.1 in floats and doubles. Now, using a float gives you a small error. Using a double gives you an even smaller error. The problem now is, that by casting the float
to a double
you carry over the bigger of error of the float
. Of course they aren't gone compare equal now.
而不是使用(float)0.1
,你可以使用 0.1f
这是一个更好阅读。
Instead of using (float)0.1
you could use 0.1f
which is a bit nicer to read.
这篇关于比较浮点在目标C中的奇怪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!