ios - calculations in objective-c not returning the correct value -


please check out piece of code, more 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 calculation various steps correct answer can explain why hourstep5 doesn't produce hourstep4 produces?

it's difference between integer division , floating-point division.

this line:

float hourstep3 = hourstep2 / 24; 

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

in combined calculation, dealing integers (without converting floats in between), so

(h + (m / 60)) / 24 

evaluates 13 / 24 equals 0 (integer division). change to

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

and same result above.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -