iphone / Objective C - Comparing doubles not working

后端 未结 2 1176
庸人自扰
庸人自扰 2020-12-03 17:53

I think I\'m going insane. \"counter\" and \"interval\" are both doubles. This is happening on accelerometer:didAccelerate at an interval of (.01) . \"counter\" should even

2条回答
  •  时光取名叫无心
    2020-12-03 18:26

    In your else block, you are not adding 0.01 to counter, because that is not a representable double-precision value. You are actually adding the value:

    0.01000000000000000020816681711721685132943093776702880859375
    

    Unsurprisingly, when you repeatedly add this value to itself, you never get 0.5 exactly.

    Two options: the better is to replace the if condition with (counter >= interval). Alternatively, you could use a small power of two for the increment instead of something that cannot be represented, like 0.0078125.

提交回复
热议问题