objective-cfloating-pointuiscreen

Why is float multiplication showing 0


float yLimit = [[UIScreen mainScreen] bounds].size.height;
yLimit = yLimit * (2/3);
NSLog(@"ylimit: %f", yLimit);

the nslog yields 0.0.

Huh?


Solution

  • Change your code from

    yLimit = yLimit *(2/3);

    to

    yLimit = yLimit *2/3;

    When the 2/3 division occurs you get 0. (Zero) then 0 multiplied by yLimit yields 0

    2/3 is equivalent to Int/Int which results in an Int instead of Double or Float which the questioner was expecting.

    Well, yLimit * (2/3) results to yLimit * 0, as 2/3 = 0.6666666667, but it round off to 0 due to implicitly integer types