Reputation:
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.
Upvotes: 6
Views: 8916
Reputation: 103
Its all about how data is stored in memory.
Let me first tell that how long and float are stored in memory.
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
).
Upvotes: 2
Reputation: 55543
%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).
Upvotes: 6
Reputation: 12287
%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
.
Upvotes: 6