Given a float f = 43.20, what do these printf conversions produce?
#include
int main()
{
float f = 43.20;
printf("%e, ", f);
printf("%f, ", f);
printf("%g", f);
return 0;
}
Assume typical IEEE-754 and default precisions for %e, %f, and %g.
-
A4.320000e+01, 43.200001, 43.2
-
B4.3, 43.22, 43.21
-
C4.3e, 43.20f, 43.00
-
DError
-
ENone of the above
Answer
Correct Answer: 4.320000e+01, 43.200001, 43.2
Explanation
Introduction / Context:The format specifiers %e, %f, and %g print floating-point values differently. Understanding each specifier and the effect of binary rounding explains the exact output.
Given Data / Assumptions:
- %e prints in exponential notation with six fractional digits by default.
- %f prints fixed-point with six fractional digits by default.
- %g chooses either %f or %e in a compact form, trimming trailing zeros.
- float values are promoted to double when passed to printf.
Concept / Approach:Compute how each format represents 43.20. Due to binary rounding, the closest representable float near 43.20 may be slightly larger than 43.2, leading to 43.200001 with %f.
Step-by-Step Solution:%e → "4.320000e+01".%f → prints six decimals → "43.200001" on many systems because 43.20 is not exactly representable in binary.%g → compact form → "43.2".
Verification / Alternative check:Printing with higher precision (e.g., "%.9f") will reveal the tiny rounding difference more clearly.
Why Other Options Are Wrong:They contain impossible suffixes (like "f" in output) or arbitrary rounding that does not match default printf behavior.
Common Pitfalls:Expecting %f to always show exactly the decimal literal; forgetting argument promotion of float to double in variadic functions.
Final Answer:4.320000e+01, 43.200001, 43.2