scanf is collecting the wrong input

前端 未结 3 1514
花落未央
花落未央 2021-01-29 08:13
 #include 
 int main(void)
 {
      double c;
      scanf(\"%f\", &c);
      printf(\"%f\", c);
 }

This is an exerpt from a program

相关标签:
3条回答
  • 2021-01-29 08:21

    the outputTry %lf instead of %f

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

    What you've used is %f, which is used for a regular float datatype. since you've specified double , you need to use %lf , which is long float. it reads a double. hope this helps you.

    0 讨论(0)
  • 2021-01-29 08:29

    "%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

    Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).

    0 讨论(0)
  • 2021-01-29 08:41

    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.

    0 讨论(0)
提交回复
热议问题