Getting a Decimal Result
If you want a decimal result, at least one of the two numbers has to be a decimal number:
printf("%f\n", 7 / 2.0);
printf("%.1f\n", 7.0 / 2);This prints:
3.500000
3.5The result is a double, so you print it with %f or %.1f. With %d, it would be a compile error, as you know.
A typical mistake is to think that storing the result in a double is enough:
double half = 7 / 2;
printf("%f\n", half);This prints:
3.000000C calculates 7 / 2 first. Both numbers are whole, so the result is 3, and only then is that 3 stored in half. The type of the variable on the left of = doesn't change how the right side is calculated.
The same thing happens with variables. A player scored 17 points in 4 games. What's the average?
int points = 17;
int games = 4;
double average = points / games;
printf("Average: %.2f\n", average);This prints:
Average: 4.00That's wrong: the right answer is 4.25. You can't add .0 to a variable, but you can convert its value to a double. Write the type in parentheses in front of it:
int points = 17;
int games = 4;
double average = (double)points / games;
printf("Average: %.2f\n", average);This prints:
Average: 4.25(double)points takes the value of points as a decimal number, 17.0. And a decimal number divided by a whole number gives a decimal result. The variable points itself stays an int. This kind of conversion is called a cast.
Watch where you put it. (double)(points / games) doesn't help: the parentheses make C divide first, and only the result, 4, is converted to 4.0.
Instructions
The friends split the pizza bill of 50 EUR equally. Run the program: it prints 12.00, so 2 EUR of the bill is missing. Fix the calculation of each with (double), so that the program prints Each pays: 12.50 EUR.
The pizzas were cut into 18 slices. On the next line, print what one slice costs. This time, write 18 straight into the calculation as a decimal number, 18.0:
One slice: 2.78 EURStart programming for free
8/11