6

I'm not sure what I'm doing wrong, but I'm not able to read a double from the console. Reading an it works fine for some reason. I'm using Xcode.

double n1;

// get input from the user
printf("Enter first number: ");
scanf("%f", &n1);

printf("%f", n1);

This will always print 0 no matter what I enter.

  • Possible duplicate of [Variable of type double not working when read by scanf()](https://stackoverflow.com/questions/37285056/variable-of-type-double-not-working-when-read-by-scanf) – phuclv Sep 09 '18 at 04:32

3 Answers3

6

%f is looking for a float, not a double. If you want to use a double, use the format %lf.

As a somewhat interesting aside, clang warns about this without any extra flags, gcc 4.6 won't warn about it even with -Wall -Wextra -pedantic.

Collin
  • 11,977
  • 2
  • 46
  • 60
5

%f is meant for a single precision floating-point value (float). The format specifier you need is %lf, meaning long precision floating-point value (double).

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
2

Its all about how data is stored in memory.
Let me first tell that how long and float are stored in memory.

  • A double (long float, 64 bits) is stored in memory like or this (little endian notation).
  • Where as a float (32 bits) is stored like this (little endian notation).
    Also have a look at this "en.wikipedia.org/wiki/Floating_point#Internal_representation" (all floating data types)

So here you are asking to take input as %f (i.e. float, which is 4 bytes but double is 8 bytes), so compiler takes input from console and converts it to float type and stores it at memory location(which is actually 8 bytes) of variable (here n1).

Chokho
  • 103
  • 1
  • 5
  • little endian and big endian http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html – Chokho Mar 25 '12 at 15:26