#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?
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.