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.
The
%ldformat string means that it’s expecting to read in along signed int, but you’re passing it instead adouble. You should instead use the%lfformat specifier to say that you want adouble.Note that for
scanf, thelis required fordoubles (and is required to be absent forfloats), whereas forprintf, thelin%lfhas no effect: both%fand%lfhave the same output for bothfloats anddoubles, due to default argument promotion.