int vs float: Truncation, Binary, and Choosing the Right Specifier

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 float type for numbers with a fractional part
  • Find out why printing a float with %d gives nonsense
  • Use %f and %.2f to 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

TypeHoldsprintf specifierExample
intwhole numbers%d11
floatnumbers with a fractional part%f, %.2f12.800000, 12.80
doublelike float, with more precision%f12.800000
chara single character%cA

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 2 in %.2f.

Quick check

  1. What is stored in n after int n = 7.99;?

    Show answer

    7. The fractional part is truncated, not rounded.

  2. A program prints a float using %d and shows a huge negative number. Is the variable’s value wrong?

    Show answer

    No. The value is fine. The specifier tells printf to interpret it as an int, so the bits are read the wrong way. Use %f.

  3. What does printf("%.1f\n", 3.25 + 1.5); print?

    Show answer

    4.8 (the value is 4.75, displayed to one decimal place).

  4. Does %.2f change 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)

Variables and Format Specifiers: Printing Values with %d

In the previous lesson you created two variables, x and y, and the compiler warned that you never used them. In this lesson you put them to work. You add them together, print the answer, and then make a mistake that the compiler cannot catch for you.

In this lesson you will

  • Declare, assign and initialise int variables
  • Print the value of a variable with the format specifier %d
  • See how printf matches placeholders to values, in order
  • Meet your first logical error: a program that builds and runs, but gives the wrong answer

Try it: store and add two numbers

Start from your program from the previous lesson. Below y = 6;, add a third variable that holds the sum, and change the message so that it prints the sum:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y;
    y = 6;
    int sum = x + y;
    printf("The sum is %d\n", sum);
    return 0;
}
The sum is 11

The warnings from the previous lesson have gone, because every variable is now used. Notice that you cannot simply write the word sum inside the quotes. That would print the letters s-u-m. Instead, you leave a placeholder, %d, where the number should go, and pass sum after a comma.

Now change one thing. Make the message more informative by printing all three numbers. Before you build, think about which value lands in which %d:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y;
    y = 6;
    int sum = x + y;
    printf("The sum of %d and %d is %d\n", sum, x, y);
    return 0;
}

Break it on purpose: put the values in the wrong order

Build and run the program above. Observe:

The sum of 11 and 5 is 6

There are no errors and no warnings, and the program ran. But 11 plus 5 is not 6! Before reading on, look at the line of code and work out why the computer printed exactly this.

Now fix it so that the values are listed in the same order as the sentence: x, then y, then sum.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y;
    y = 6;
    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

What just happened

printf fills its placeholders strictly from left to right. The first %d gets the first value after the string, the second %d gets the second value, and so on. It has no idea what your sentence means. In the broken version the first value was sum (11), so the sentence began “The sum of 11”. The computer did exactly what it was told.

This kind of mistake is called a logical error. The code follows every rule of C, so it builds and runs, but it does not do what you intended. Compare it with the syntax errors from the previous lesson, which the compiler refuses to build. Logical errors are found by testing: work out the answer you expect (5 + 6 = 11) and check that the program agrees.

Break it on purpose: forget a comma

In the fixed program, delete the comma between x and y so that the line ends x y, sum);. Build it:

main.c:10:45: error: expected ')' before 'y'

This time it is a syntax error, and the build fails. A printf call is a string literal followed by a comma-separated list of values, and every value needs its comma. Put the comma back and build again.

Name it: declaring, assigning and initialising

Your program now uses three slightly different ways to create and fill a variable. Each one has a name:

  • int y; is a declaration. It tells the compiler the variable’s type (int, a whole number) and its identifier (its name, y). No value is given yet.
  • y = 6; is an assignment. It stores a value in a variable that already exists.
  • int x = 5; is a declaration with initialisation. It creates the variable and gives it a first value in one statement.
  • int sum = x + y; also initialises, using the result of a calculation.

A format specifier such as %d tells printf two things: where a value goes in the text, and how to display it. %d means “display an int as a decimal (base-10) whole number”. Other types need other specifiers, which is the subject of the next lesson.

Your turn: start a reference table. Search for the common printf format specifiers and start a table with three columns: data type, specifier, example. Add int → %d now, and keep adding rows as the series goes on.

Key terms

  • Variable: a named storage location in memory that holds a value of a particular type.
  • Declaration: introduces a variable’s type and identifier, e.g. int y;
  • Assignment: stores a value in an existing variable, e.g. y = 6;
  • Initialisation: gives a variable its first value when it is declared, e.g. int x = 5;
  • Format specifier: a placeholder such as %d that marks where, and how, a value is printed.
  • Logical error: the program builds and runs but produces the wrong result.

Quick check

  1. What does printf("%d minus %d\n", y, x); print when x is 5 and y is 6?

    Show answer

    6 minus 5. The first %d takes the first value listed (y).

  2. Is “The sum of 11 and 5 is 6” caused by a syntax error or a logical error? How would you notice it?

    Show answer

    A logical error. The program builds and runs. You notice it by testing: compare the output with the answer you worked out yourself.

  3. Which line is a declaration with initialisation: int a;, a = 3; or int b = 3;?

    Show answer

    int b = 3;. It declares b and gives it a first value in the same statement.

  4. What happens if a printf has three %d placeholders but only two values after the string?

    Show answer

    GCC warns format '%d' expects a matching 'int' argument. If you run it anyway, the third number printed is meaningless. Always match each placeholder to one value.

Optional: a recorded demonstration of these steps starts around 33:00.

Part of the Introduction to C series. Next: int vs float: Truncation, Binary, and Choosing the Right Specifier