Your addition program works perfectly for 5 and 6. But what about 5.9 and 6.9? In this lesson you feed it numbers with decimal places and watch it quietly get the answer wrong, twice, in two different ways. Each mistake teaches you something about how C stores numbers.
In this lesson you will
- See what happens when a decimal number is stored in an
int - Switch to the
floattype for numbers with a fractional part - Find out why printing a
floatwith%dgives nonsense - Use
%fand%.2fto print floats properly
Try it: decimals in an int
Here is the addition program, tidied so that each variable is initialised on one line. Change the values to 5.1 and 6.1, then build and run:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5.1;
int y = 6.1;
int sum = x + y;
printf("The sum of %d and %d is %d\n", x, y, sum);
return 0;
}
The sum of 5 and 6 is 11
No errors, and no warnings either. The program simply ignored the .1. Maybe it rounded? Test that idea: change the values to 5.9 and 6.9. If C rounded, you would expect 6 and 7.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5.9;
int y = 6.9;
int sum = x + y;
printf("The sum of %d and %d is %d\n", x, y, sum);
return 0;
}
The sum of 5 and 6 is 11
Still 5 and 6. When a decimal value is stored in an int, C does not round it. It truncates it: everything after the decimal point is thrown away. An int can only ever hold whole numbers.
Try it: switch to float
To store numbers with a fractional part, use the type float (short for floating-point number). Change all three variables to float, but leave the %d specifiers as they are for now:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float x = 5.9;
float y = 6.9;
float sum = x + y;
printf("The sum of %d and %d is %d\n", x, y, sum);
return 0;
}
Break it on purpose: print a float with %d
Build the program above and look at the build log first. GCC warns, once for each value:
main.c:9:25: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
It is only a warning, so the program still runs. Observe: the output is nonsense. Your numbers will be different, and they may even change each time you run it. Here is one run:
The sum of -1238979704 and -1238979688 is -299069992
Nothing in the variables is wrong. x really does hold 5.9 now. The problem is entirely in how you asked for it to be displayed.
What just happened
Inside the computer, every variable is stored as a pattern of binary digits (0s and 1s). Even 5.9 is stored as 0s and 1s. An int and a float use completely different patterns. A float stores a sign, a set of significant digits and an exponent, a bit like scientific notation in binary.
A format specifier tells printf how to interpret the value it is given. %d says “this is an int”. Hand it a floating-point value and it reads the bits as if they were an integer. On many computers it even looks in the wrong place entirely, because floating-point values are passed differently. The computer did exactly what the specifier told it to do. That is why this is a logical error, and why the compiler can only warn you, not stop you. (The warning mentions double because printf receives a float as a double, a larger floating-point type.)
Try it: the right specifier
The specifier for floating-point numbers is %f. Change all three:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float x = 5.9;
float y = 6.9;
float sum = x + y;
printf("The sum of %f and %f is %f\n", x, y, sum);
return 0;
}
The sum of 5.900000 and 6.900000 is 12.800000
Correct at last, but six decimal places is a lot. You can control this by putting a dot and a number between the % and the f. %.2f means “show 2 decimal places”:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float x = 5.9;
float y = 6.9;
float sum = x + y;
printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
return 0;
}
The sum of 5.90 and 6.90 is 12.80
%.2f only changes the display. The value stored in sum is not rounded. Printing the same variable with different precisions makes this easy to see:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float price = 12.8;
printf("%.0f\n", price);
printf("%.1f\n", price);
printf("%.3f\n", price);
return 0;
}
13 12.8 12.800
Name it: data types and their specifiers
| Type | Holds | printf specifier | Example |
|---|---|---|---|
int | whole numbers | %d | 11 |
float | numbers with a fractional part | %f, %.2f | 12.800000, 12.80 |
double | like float, with more precision | %f | 12.800000 |
char | a single character | %c | A |
Add these rows to the reference table you started in the previous lesson.
Key terms
int: a type for whole numbers.float: a type for floating-point numbers, which have a fractional part.- Truncation: discarding everything after the decimal point (not rounding).
- Binary: base 2. All data in memory is stored as patterns of 0s and 1s.
%f/%.2f: print a floating-point value with 6 or with 2 decimal places.- Precision (in a format specifier): the number after the dot, e.g. the
2in%.2f.
Quick check
What is stored in
nafterint n = 7.99;?Show answer
7. The fractional part is truncated, not rounded.A program prints a
floatusing%dand shows a huge negative number. Is the variable’s value wrong?Show answer
No. The value is fine. The specifier tells
printfto interpret it as anint, so the bits are read the wrong way. Use%f.What does
printf("%.1f\n", 3.25 + 1.5);print?Show answer
4.8(the value is 4.75, displayed to one decimal place).Does
%.2fchange the value stored in a variable?Show answer
No. It only affects how the value is displayed.
Optional: a recorded demonstration of these steps starts around 38:40.
Part of the Introduction to C series. Next: Reading Input with scanf (and Defensive Initialization)