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);
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:
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, orcwere afloat(or cast thereto) the equation would also work.That’s because an expression in which either operand is a
floatwill cause the other (integer) operand to be promoted to afloat, too, at which point the result of the expression will also be afloat.