比较objective-C中的浮点数的奇怪问题 [英] Strange problem comparing floats in objective-C

查看:22
本文介绍了比较objective-C中的浮点数的奇怪问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在算法中的某个时刻,我需要将类属性的浮点值与浮点数进行比较.所以我这样做:

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 是一个浮点属性.

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) {
}

这很好用.

谁能向我解释为什么会这样?0.1 是默认定义为 double 还是什么?

Can anyone explain to my why this is happening? Is 0.1 defined as a double by default or something?

谢谢.

推荐答案

我相信,没有找到这样说的标准,当比较 floatdouble 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 的精确表示.现在,使用浮点数会给您带来一个小错误.使用 double 会给你一个更小的错误.现在的问题是,通过将 float 转换为 double,您会继承 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.

您可以使用 0.1f 而不是使用 (float)0.1,它更易于阅读.

Instead of using (float)0.1 you could use 0.1f which is a bit nicer to read.

这篇关于比较objective-C中的浮点数的奇怪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆