Quote:
Originally Posted by JohnC
If you add 0.5, it will "round" to the nearest integer:
int x = (int)(40/9 + 0.5); // 40/9 = 4.444 repeating and rounds down to 4
int y = (int)(40/6 + 0.5); // 40/6 = 6.666 repeating, rounds up to 7
|
Nope - In C (and most languages), integer division will result in immediate truncation, not just truncation at the end. since the dividend and the divisor are both integers, it will calculate 40/9 to be 4, then add 0.5, then truncate as you put it into the integer, giving you 4 for the answer. 40/6 will calculate to 6, add 0.5 and truncate again and you'll get 6.
Instead, what you can try (for your example) is the following:
int x = (int)(40.0/9.0 + 0.5); // 40/9 = 4.444 repeating and rounds down to 4
int y = (int)(40.0/6.0 + 0.5); // 40/6 = 6.666 repeating, rounds up to 7
by adding the ".0" to the divisor and the dividend, you turn the division into a floating point operation, instead of an integer operation. That means that it won't truncate the result of the division, only the final result of the equation as you stick it into an integer. To accomplish this using variables instead of straight numbers, by far the easiest way is to typecast the variables:
int x = (int)(((float)dividend)/((float)divisor) + 0.5);
That tells the compiler that, for this one instance, you want it to treat the variables as floats instead of integers, meaning that it won't truncate any results in mid-computation.