Reputation: 13661
I am learning C and I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
double x;
printf("x = ");
scanf("%ld", &x);
printf("x = %lf\n", x);
system("PAUSE");
return 0;
}
(I am using Dev C4.9, Windows XP SP3)
When I run the above program and entered 5.3; the program printed x = 0.000000
Can anyone explain why is that, please?
Thanks a lot.
Upvotes: 1
Views: 1045
Reputation: 20640
It's better to use gets()
and then try to parse and convert the entered string to the desired type.
Because everything is input initially as a string and it's easier to handle bad input.
scanf requires the input to be perfect and that doesn't always happen when humans are keying in data.
Upvotes: -1
Reputation: 3391
Be consistent with the data with scanf and printf. Plus for %lf(double), %f(float), %lld(long long int) i've experienced problem in windows. It's not well implemented in windows (msvcrt.dll if you ask).
Upvotes: 0
Reputation: 25058
for your scanf
ld:
same as "%d" except argument is "long" integer. Since "long"
is the same as "int" on GCOS8,this is the same as "%d". However, the compiler
will warn you if you specify "%ld" but pass a normal "int", or specify "%d" but
pass a "long".
for your printf
lf:
same as "%f" except argument is "long double".
Since "long double" is the same as "double" on GCOS8, this is the same as "%f".
Upvotes: 0
Reputation: 400622
The %ld
format string means that it's expecting to read in a long signed int
, but you're passing it instead a double
. You should instead use the %lf
format specifier to say that you want a double
.
Note that for scanf
, the l
is required for double
s (and is required to be absent for float
s), whereas for printf
, the l
in %lf
has no effect: both %f
and %lf
have the same output for both float
s and double
s, due to default argument promotion.
Upvotes: 4