objective c - Incrementing a double is never whole -
in objective-c have timer fire every 0.1 seconds , increment double value (seconds) 0.1.
so should keep time counting 1/10 of second. when fires checks if
-else
statements see if time (seconds) equal 3, 9, 33, etc., these never triggered. suppose because of way doubles represented in bits, decimal approximation , never whole number.
how can fix statements triggered?
-(void)timeseconds:(nstimer*)thetimer { seconds = seconds + 0.1; nslog(@"%f", seconds); if (seconds == 3.0) { [player pause]; [secondstimer invalidate]; } else if (seconds == 9){ [player pause]; [secondstimer invalidate]; }
the floating point types cannot represent numbers exactly, when these added, error compounded , floating point type becomes less , less precise.
use integral type represent time difference using greater resolution, example, use nsuinteger
represent milliseconds instead of seconds, , increment 100 instead of 0.1. instead of comparing seconds == 3.0
, use milliseconds == 3000
, etc.
keep in mind timers not fired precisely:
a timer not real-time mechanism; fires when 1 of run loop modes timer has been added running , able check if timer’s firing time has passed.
you may find when milliseconds==9000
, more 9 seconds has passed (but not more). there other tools available if more precise timing required.
Comments
Post a Comment