Search code examples
cdoublescanfstdio

scanf is collecting the wrong input


 #include<stdio.h> 
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.


Solution

  • You need to use "%lf" for double.

    This is the warning from clang compiler.

    warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat] scanf("%f", &c);

    Here is the scanf reference. It's format is %[*][width][length]specifier. The specifier for 'floating point number' is f. So we use %f to read float x. To read double x, we need to specify the length as l. Combined the format is %lf.