Variable of type double not working when read by scanf()

眉间皱痕 提交于 2019-12-13 09:48:53

问题


#include <stdio.h>

int main(){
    double d;

    scanf("%f", &d);
    printf("%f\n\n",  d);

    system("pause");
    return 0;
}

This is what I get: error.

This code is meant to read the variable double and display it on the screen but it does only display "0.0...".

If I just change the variable type to float it does exactly what I want but if I make it a double it just reads '0'. Why?


回答1:


In your code,

 scanf("%f", &d);

is wrong. For scanf(), %f expects a pointer to float as argument.

Quoting C11, chapter §7.21.6.2, fscanf()

a,e,f,g

Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

In case you want to scan a double, you have to use

 scanf("%lf", &d);

FWIW, passing incompatible type of argument for any format specifier invokes undefined behavior.

Quoting C11,

[...] Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.



来源:https://stackoverflow.com/questions/37285056/variable-of-type-double-not-working-when-read-by-scanf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!