Decimal Numbers
An int holds only whole numbers. But a price can have cents, and a height can be 1.68 m. For numbers with a decimal part, C has the type double:
double price = 12.5;In C, decimal numbers are always written with a decimal point: 12.5, -0.25, 3.0.
To print a double, use %f instead of %d (f as in floating point, the way computers store decimal numbers). %f always prints six decimal places. Usually, you want fewer, so write their number between % and f, after a dot: %.2f prints two decimal places, %.1f one. The number is rounded:
double price = 12.5;
double pi = 3.14159;
printf("%f\n", price);
printf("%.2f\n", price);
printf("%.1f\n", price);
printf("%.2f\n", pi);This prints:
12.500000
12.50
12.5
3.14For prices, %.2f is just right: two decimal places, as on a receipt.
The format specifier must fit the value: %d for an int, %f for a double. printf itself can't check what it gets; it trusts the format string. On another computer, a wrong specifier could print a nonsense number, so on this site, it's a compile error:
#include <stdio.h>
int main(void) {
double price = 12.5;
printf("Price: %d\n", price);
return 0;
}The compiler reports:
main.c:5:27: error: format specifies type 'int' but the argument has type 'double' [-Werror,-Wformat]The format asks for an int, but the value (the argument) is a double. Below the first line, the compiler even suggests %f. It works the other way round, too: %f with an int ends with format specifies type 'double' but the argument has type 'int'.
More typical mistakes:
- A decimal comma: in many countries, people write 12,5. In C,
double price = 12,5;ends with the errorexpected identifier or '(', because the comma means something else in C. - A decimal number in an
int:int price = 12.5;compiles, but only12is stored. The decimal part is thrown away.
Instructions
Below, create a variable price of type double with the value 24.9: the price of one notebook.
On the next line, print it with %f like this: Price: 24.900000.
Six decimal places are too many for a price. Change %f to %.2f, so that the line shows Price: 24.90.
On the next line, print how much the three notebooks cost: count * price. A calculation with a double gives a double, so use %.2f again:
Total: 74.70Start programming for free
4/11