When using double or float data type in an iPhone app, I am running into problems with ">=" and "<=" comparisons because when a variable is assigned a number entered with one decimal place, such as 4.2, the float or double used in the comparison actually may have a value such as 4.1999998092651367. Because of this difference, a comparison such as ">= 4.2" is false instead of true. How can I avoid this problem?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
Not may. will. To be specific:
The problem comes when you write something like:
f
is exactly4.19999980926513671875
, but you're comparing it to the double-precision literal "4.2", which has the value4.20000000000000017763568394002504646778106689453125
, so the comparison fails. If instead you compare against the single precision literal "4.2f":the comparison succeeds, because the values are exactly equal. Floating-point is complicated, but it is entirely deterministic; one of the simplest things you can do to make it more intuitive is to not mix precisions. If you're working with
float
, make sure all of your literals are suffixed withf
to make them single precision, too.(This can also improve performance, but that's not the reason to do it; the reason to do it is because it will make your code more correct).