scanf not working. need to read double from consol

2020-02-06 07:45发布

问题:

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.

回答1:

%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.



回答2:

%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).



回答3:

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).



标签: c io scanf