In C printf formatting, what is the rounded output for a floating value with one digit after the decimal point?
#include
int main()
{
float a = 3.15529f;
printf("%2.1f
", a);
return 0;
}
-
A3.00
-
B3.15
-
C3.2
-
D3
-
ENone of the above
Answer
Correct Answer: 3.2
Explanation
Introduction / Context:This question checks knowledge of printf's floating-point formatting and rounding behavior. The format %2.1f requests exactly one digit after the decimal point, with a minimum field width of 2.
Given Data / Assumptions:
- a = 3.15529.
- Format string is "%2.1f".
- Default rounding of printf for .1 precision is to the nearest representable, commonly half-up behavior for ties once converted to decimal.
Concept / Approach:Rounding 3.15529 to one decimal place yields 3.2. The width specifier 2 simply sets a minimum field width; it does not truncate digits beyond the requested precision nor suppress the decimal point.
Step-by-Step Solution:Desired precision = 1 decimal → round 3.15529 to 3.2.Output printed as a fixed-point number with one digit after the decimal → "3.2".
Verification / Alternative check:Printing with higher precision first (e.g., %.3f) shows 3.155, confirming the next digit is 2, so rounding to one decimal produces 3.2.
Why Other Options Are Wrong:3.15 has two decimals; 3.00 is over-rounded down; 3 is an integer-like rendering and does not match %.1f formatting.
Common Pitfalls:Confusing field width with precision, and expecting integer output for %f.
Final Answer:3.2