Search code examples
objective-ciosfloorceil

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 hourStep1 = 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?


Solution

  • 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.