C/C++ Arena

Step 4 of 6

Decimals with double

An int can only hold whole numbers. If you need a fraction, like an accuracy of 0.625 or a price of 19.99, use the type double (short for "double-precision floating point"). Print a double with %f.

#include <stdio.h>

int main(void) {
    double accuracy = 0.625;
    double price = 19.5;
    printf("%f\n", accuracy);
    printf("%.2f\n", accuracy);
    printf("%.1f\n", price);
    return 0;
}
0.625000
0.62
19.5

Controlling decimals

Plain %f always shows six digits after the decimal point. Put .N between the % and the f to choose how many: %.2f shows two, %.0f shows none. The value is rounded for printing; the variable itself isn't changed. 0.625 is exactly halfway between 0.62 and 0.63, and for exact ties like this printf rounds to the even last digit, so it prints 0.62 (and %.0f prints 2.5 as 2 but 3.5 as 4). Values that aren't exact ties round the way you'd expect.

How exact are doubles?

A double stores about 15 to 16 significant digits, which is plenty for most things, but it stores numbers in binary, so many decimal fractions (like 0.1) are tiny approximations. That's why you should never use double for money in real software: store cents in an integer instead. For scores, ratios and measurements, double is the right choice.

Common mistakes

Your task

Store 1.25 in a double named rating and print it with exactly two decimals so the output is Rating: 1.25.

Challenge 2

Store 45.678 in a double named accuracy and print it rounded to one decimal, so the output is Accuracy: 45.7.

Challenge 3

A player's eDPI is their mouse sensitivity times their mouse DPI. Declare a double named sens equal to 1.75 and an int named dpi equal to 400, compute the eDPI into a double, and print:

Sensitivity: 1.75
eDPI: 700.00

Previous: Changing a variable Next: Characters with char