Same Calculation, different result?

My goal is to calculate how many percent counter out of cap is. Now I ran over a problem, I can't find the difference between the two formulas below, as far as my mathematical understanding tells me, it's exactly the same calculation. But only the first one works, brackets make no difference.

int i = counter * 100 / cap; //works
int i = counter / cap * 100; //doesn't work

Has this got something to do with java or is it just me who's made a horrible thinking mistake?

Jon Skeet
people
quotationmark

Your mistake is assuming that these are just pure, abstract numbers. I assume that counter is an int... so the second version is evaluated as:

int tmp = counter / cap;
int i = tmp * 100;

Now we're dealing with integer arithmetic here - so if counter is in the range [-99, 99] for example, tmp will be 0.

Note that even your first version may not work, either - if counter is very large, multiplying it by 100 may overflow the bounds of int, leading to a negative result. Still, that's probably your best approach if counter is expected to be in a more reasonable range.

Even with floating point arithmetic, you still don't get the behaviour of "pure" numbers, of course - there are still limits both in terms of range and precision.

people

See more on this question at Stackoverflow