C/C++ Arena

Step 3 of 5

Reading doubles

Here's a quirk you just have to memorize: printf uses %f to print a double, but scanf needs %lf ("long float") to read one.

Type print with read with
int %d %d
double %f %lf
char %c %c

The reason is history: when you pass a value to printf, a float is automatically converted to double, so %f works for both. scanf receives an address instead, and it must know whether the box at that address is a 4-byte float or an 8-byte double. Using %f with a double writes the wrong number of bytes and gives nonsense.

#include <stdio.h>

int main(void) {
    double km;
    scanf("%lf", &km);
    double miles = km * 0.621371;
    printf("%.2f km = %.2f miles\n", km, miles);
    return 0;
}
42.195
42.20 km = 26.22 miles

Formulas with doubles

When a formula mixes a double with int literals, like km * 0.621371 or c * 9 / 5 + 32, C works left to right with precedence: c * 9 is a double (because c is), so / 5 is a real division too. The integer-division trap only bites when both sides of / are ints. If you wrote 9 / 5 * c, the 9 / 5 would be done first as ints and give 1, which is wrong.

Your turn: read a temperature in Celsius and print it in Fahrenheit with one decimal. The formula is f = c * 9 / 5 + 32.

Input 100 prints 212.0. Input 36.6 prints 97.9.

Previous: Several values at once Next: Characters and words