Formatting and Numeric Conversion
Keep the fraction before you print
A market stall has five apples to share across two baskets. Integer division gives two whole apples per basket, but the average is two and a half. Storing an already-truncated result in a double cannot recover the missing half.
#include <stdio.h>
int main(void) {
int apples = 5;
int baskets = 2;
double average = (double) apples / baskets;
printf("Apples: %d; per basket: %.2f\n", apples, average);
return 0;
}
(double) apples is a cast: it converts the value read from apples for this calculation without changing the variable's type. Because one operand is now a double, C converts the other operand to double too. The division uses 5.0 and 2.0, giving 2.5; %.2f displays that result as 2.50.
Compare the steps:
| Expression | Division performed | Value stored in a double |
|---|---|---|
apples / baskets | Integer division: 5 / 2 | 2.0 |
(double) apples / baskets | Floating-point division: 5.0 / 2 | 2.5 |
Read the format from left to right
#include <stdio.h>
int main(void) {
char aisle = 'C';
double weight = 1.25;
printf("Aisle %c: %.2f kg\n", aisle, weight);
return 0;
}
%c receives aisle, a character, and %.2f receives weight, a double. The output is Aisle C: 1.25 kg. A wrong conversion is not a harmless display choice; match it to the argument's type.
Run both examples and identify which decimal digits come from the values and which come from the requested precision. The next exercise needs a whole-number total, so it will use int and %d instead.