Example 1 — Integer division versus a cast
Convert before dividing to keep the fractional part.
#include <stdio.h>
int main(void) {
int sum = 7;
int count = 2;
double wrong = sum / count;
double right = (double)sum / count;
printf("wrong: %.1f\n", wrong);
printf("right: %.1f\n", right);
return 0;
} How It Works
sum / countdivides two ints and yields3, then converts to3.0.(double)sumconverts first, so the division is floating point.- Casts bind tighter than
/.
