f.perdition
f.perdition

Reputation: 205

calculations in Objective-C

Could anyone explain to me why this keeps returning 0 when it should return a value of 42? it works on paper so i know the math is right I'm just wondering as to why it isn't translating across?

    int a = 60;
    int b = 120;
    int c = 85;
    int progress;

    progress = ((c-a)/(b-a))*100;

    NSLog(@"Progess = %d %%",progress);

Upvotes: 1

Views: 834

Answers (4)

Alnitak
Alnitak

Reputation: 339816

It's because your math is all using integers.

In particular, your inner expression is calculating 25 / 60, which in integer math is zero.

In effect you have over-parenthesised your expression, and the resulting order of evaluation is causing integer rounding problems.

It would have worked fine if you had just written the formula so:

progress = 100 * (c - a) / (b - a);

because the 100 * (c - a) would first evaluate to 2500, and would then be divided by 60 to give 41.

Alternative, if any one (or more) of your variables a, b, or c were a float (or cast thereto) the equation would also work.

That's because an expression in which either operand is a float will cause the other (integer) operand to be promoted to a float, too, at which point the result of the expression will also be a float.

Upvotes: 8

Alex
Alex

Reputation: 3181

c - a will give you 25

b - a will give you 60

Since a, b, and c are all integers, meaning they can't be decimals. Therefore, by doing (c-a)/(b-a), you will get 0, instead of 0.41666666 because in integer division, anything after the decimal point will get cut off, leaving the number before the decimal point.

To make it work the way you wanted it to, you should try casting (c-a) and (b-a) to either double or float:

progress = ((float)(c-a) / (float)(b-a)) * 100;

or

progress = ((double)(c-a) / (double)(b-a)) * 100;

Upvotes: 3

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

Because (c - a) / (b - a) is computed using integer math.

To fix, cast to a float before dividing:

progress = (int)((((float)(c - a)) / ((float)(b - a))) * 100);

Upvotes: 1

simont
simont

Reputation: 72547

a,b and c are ints. When you calculate ((c-a)/(b-a)), the result is also an int; the real value is a decimal (0.42), but an int can't take a decimal number, so it rounds to 0, which is multiplied by 100 to get 0.

Upvotes: 1

Related Questions