UIProgressView progress multiplied by a number returning weird results
So I have the following code:
angle = progbm.progress * 30;
NSLog(@"%d,%f", angle, progbm.progress);
progbm is a UIProgressView (running from 0.0 to 1.0) and angle is a short.
Elsewhere I have code that updates the progress bar either up or down by 0.1. I then seem to get some weird results. Here is the console output:
2011-05-14 15:21:25.265 AppTest[768:307] 3,0.100000
2011-05-14 15:21:26.238 AppTest[768:307] 6,0.200000 2011-05-14 15:21:27.245 AppTest[768:307] 9,0.300000 2011-05-14 15:21:28.061 AppTest[768:307] 12,0.400000 2011-05-14 15:21:28.940 AppTest[768:307] 15,0.500000 2011-05-14 15:21:29.820 AppTest[768:307] 18,0.600000 2011-05-14 15:21:30.716 AppTest[768:307] 21,0.700000 2011-05-14 15:21:31.6开发者_运维知识库44 AppTest[768:307] 24,0.800000 2011-05-14 15:21:32.860 AppTest[768:307] 27,0.900000 2011-05-14 15:21:34.460 AppTest[768:307] 30,1.000000 2011-05-14 15:21:39.020 AppTest[768:307] 27,0.900000 2011-05-14 15:21:40.173 AppTest[768:307] 23,0.800000How does 0.800000 * 30 equal 23?
There are two answers to this, either
1) use round() to get the integer value for the short.
2) dont use a short and use a float instead.
I eventually used option 2
My guess is rounding errors that aren't shown with the precision of the NSLog's print. When you subtract 0.1 from 1.0, you don't necessarily get 0.9. If I remember correctly, it is impossible to represent exactly 0.1 in floating point notation, because in binary it's a repeating decimal. So you'll end up with something like 0.899999 or 0.90000001. Then when you subtract another 0.1 from that, it looks like you're ending up with 0.7999999999 which NSLog is rounding to 0.800000 for printing, but integer multiplication always rounds down, so 23.9999999 is rounded down to 23.
You aren't taking into account that the progress is progressing. :-) It changes between your calculation and your displaying. Store progbm.progress into a variable which you use for calc and display and your problem will go away.
精彩评论