开发者

calculations in objective-c not returning the correct value

Please check out this piece of code, more specifically the hourStep calculations.

int h = [[timeArray objectAtIndex:0] intValue];
int m = [[timeArray objectAtIndex:1] intValue];
int s = [[timeArray objectAtIndex:2] intValue];
int mm = [[timeArray objectAtIndex:3] intValue];

NSLog([NSString stringWithFormat:@"time h:%d, m:%d, s:%d, mm:%d", h, m, s, mm]);
//time h:13, m:7, s:55, mm:105

float hourStep开发者_开发问答1 = m / 60;
float hourStep2 = h + hourStep1;
float hourStep3 = hourStep2 / 24;
float hourStep4 = hourStep3 * 15;

int hour1 = ceil(hourStep4);

NSLog([NSString stringWithFormat:@"hourStep1: %f, hourStep2: %f, hourStep3: %f, hourStep4: %f result: %d", hourStep1, hourStep2, hourStep3, hourStep4, hour1]);
//hourStep1: 0.000000, hourStep2: 13.000000, hourStep3: 0.541667, hourStep4: 8.125000 result: 9

float hourStep5 = ((h + (m / 60)) / 24) * 15; 
NSLog([NSString stringWithFormat:@"hourStep5: %f", hourStep5]);

//hourStep5: 0.000000

I have broken down the calculation into the various steps to get the correct answer but can anyone explain why hourStep5 doesn't produce what hourStep4 produces?


It's the difference between integer division and floating-point division.

This line:

float hourStep3 = hourStep2 / 24;

evaluates to 13.0f / 24 which results in 0.541667f (floating-point division).

In the combined calculation, you are only dealing with integers (without converting to floats in between), so

(h + (m / 60)) / 24

evaluates to 13 / 24 which equals 0 (integer division). Change it to

(h + (m / 60)) / 24.0f

and you will get the same result as above.


In your line

float hourStep5 = ((h + (m / 60)) / 24) * 15; 

The calculation is performed in int, not in float. Note that in C (and thus in Objective-C) the equation on the right hand side of = is performed first, without caring whatsoever the type of the left hand side (in this case, float.)

Use

float hourStep5 = ((h + (m / 60.0)) / 24) * 15; 

instead.


The whole calculation of hourStep5 will be treated as integer.

Try casting both h and m into floats in that line:

float hourStep5 = (( (float) h + ( (float) m / 60)) / 24) * 15; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜