Strange problem comparing floats in objective-C

后端 未结 7 2364
别跟我提以往
别跟我提以往 2020-11-27 16:25

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)          


        
7条回答
  •  离开以前
    2020-11-27 17:06

    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.

    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.

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

提交回复
热议问题