Step 2 of 6
The integer division trap
This is one of the most famous traps in C. When both sides of / are integers, C does integer division: it divides and throws the fractional part away. It doesn't round; it just cuts it off (truncates toward zero).
#include <stdio.h>
int main(void) {
printf("%d\n", 7 / 2);
printf("%d\n", 99 / 100);
printf("%f\n", 7.0 / 2);
printf("%f\n", (double)7 / 2);
return 0;
}
3
0
3.500000
3.500000
Why storing into a double doesn't help
double avg = 7 / 2; // avg is 3.0, not 3.5
C works out the right side first, using only what's on the right. 7 / 2 is int divided by int, so it becomes 3. Only then is 3 converted to a double and stored. The destination's type is never considered while the expression is being evaluated.
How to get a real division
If either side of / is a double, C converts the other side too and does a real division. You can:
- write a decimal literal:
7.0 / 2 - cast a variable, which means converting its value to another type for this expression:
(double)kills / rounds
A cast is written as the type in parentheses before the value. (double)kills doesn't change the variable kills; it produces a double copy of its value for this calculation.
Put the cast on one of the operands, not around the whole division: (double)(kills / rounds) still does the integer division first, and then converts the already-truncated answer.
Your turn: 25 kills over 10 rounds should print Kills per round: 2.50. Right now it prints 2.00. Fix the calculation of kpr so it does a real division.