Floating-point division
What you'll learn: How to ensure your division results include decimal places by using the correct data types.
The Integer Trap
In C, the computer looks at the "shape" of your numbers before it decides how to do math. If you divide two integers (whole numbers), C performs integer division. This means it throws away the remainder entirely.
Imagine you have 5 pizzas to share between 2 people. Mathematically, everyone gets 2.5 pizzas. However, in C, 5 / 2 equals 2. The .5 isn't rounded; it is simply deleted from existence. To keep those decimals, at least one of the numbers in your calculation must be a floating-point type (like a float or double).
Mixing Types
Think of a floating-point number as a "stronger" type. When you mix an integer and a float, C "promotes" the integer to a float so they match.
5 / 2=2(Integer / Integer = Integer)5.0 / 2.0=2.5(Float / Float = Float)5.0 / 2=2.5(Float / Integer = Float)
By adding a simple .0 to a constant, you tell the compiler, "Treat this as a decimal," which triggers the correct math.
Coding the Difference
To store a decimal result, you must use a float or double variable. If you try to store 5.0 / 2.0 into an int variable, the decimals will still be lost because the container isn't big enough to hold them.
#include <stdio.h>
int main() {
int cookies = 7;
int people = 2;
// This will result in 3, because both inputs are integers
float wrongWay = cookies / people;
// This will result in 3.5, because we use a decimal constant
float rightWay = 7.0 / 2;
printf("Wrong: %f\n", wrongWay);
printf("Right: %f\n", rightWay);
return 0;
}
In the code above, wrongWay fails because the division happens between two integers before the result is moved into the float variable. The damage is done instantly. To get 3.5, you must ensure the division itself involves a decimal.
Key takeaway
To get a decimal result, at least one number in your division must be a float or double.