中的浮点数的奇怪问题

中的浮点数的奇怪问题

本文介绍了比较 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.

您可以使用 (float)0.1 代替 (float)0.1,它更易于阅读.

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

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

08-04 02:42