float
and double
are both floating-point types
float
generally has less precision than double
float f = 1.0e9; double d = 1.0e9; f += 123.456789; d += 123.456789; printf("%f\n", f); printf("%f\n", d);
1000000128.000000 1000000123.456789
Calculations are generally carried out with double
precision.
float f = 1.0e9; double d = f + 123.456789; printf("%f\n", d);
1000000123.456789
f + 123.456789
must have used double precision.
scanf
needs to know the difference between float
and double
:
float f; double d; scanf("%f %lf", &f, &d);
float
, use %f
.
double
, use %lf
(think “long float”).
float
expressions are evaluated using
double
precision?
float
arguments to functions are promoted to double
.
printf
can’t tell the difference between a
float
and a double
argument.
%f
and %lf
work for both float
and double
in printf
.
float f = 1.2; double d = 3.4; printf("%f\n", f); printf("%f\n", d); printf("%lf\n", f); printf("%lf\n", d);
1.200000 3.400000 1.200000 3.400000