Search code examples
objective-cmathfractions

Calculate positive fractions in objective-c


I tried to calculate 4/3 and store it into a float.

float answer = 4/3;

This only returns 1. Isn't objective-c able to calculate these kinds of fractions or do I have to do it any other way?


Solution

  • If numerator and denominator are both integers, then division will be integer. Use

    float answer = 4/(float)3