Evaluate expressions before printing
Count bolts and work out an average
Two bags contain four bolts each, and three bolts are loose. Count them all, then compare the whole-number share per bag with the fractional average. The average describes the ratio; it does not mean cutting a bolt in half.
c
#include <stdio.h>
int main(void) {
int bags = 2;
int bolts_each = 4;
int extra = 3;
int bolts = bags * bolts_each + extra;
int whole_per_bag = bolts / bags;
double average = (double) bolts / bags;
printf("Bolts: %d | Whole: %d | Average: %.2f\n", bolts, whole_per_bag, average);
return 0;
}
Follow the values in statement order:
| Step | Expression | Result |
|---|---|---|
| Count all bolts | bags * bolts_each + extra | 11 |
| Divide as integers | bolts / bags | 5 |
| Convert, then divide | (double) bolts / bags | 5.5 |
Multiplication happens before addition in the first expression. For the average, the cast converts the value of bolts before division. The variable bolts itself remains an int.
Run the example and compare Whole: 5 with Average: 5.50. Converting the result of integer division afterward would only give 5.0; it cannot bring the discarded fraction back. The print precision adds the final zero for display.