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.
%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
.%f
is meant for asingle precision floating-point value
(float). The format specifier you need is%lf
, meaninglong precision floating-point value
(double).Its all about how data is stored in memory.
Let me first tell that how long and float are stored in memory.
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 (heren1
).