In C, what will this program print?
#include
#include
int main()
{
char *i = "55.555";
int result1 = 10;
float result2 = 11.111f;
result1 = result1 + atoi(i);
result2 = result2 + atof(i);
printf("%d, %f", result1, result2);
return 0;
}
Assume default float formatting with six digits after the decimal.
-
A55, 55.555
-
B66, 66.666600
-
C65, 66.666000
-
D55, 55
-
ENone of the above
Answer
Correct Answer: 65, 66.666000
Explanation
Introduction / Context:atoi converts a string to int, stopping at the first non-digit. atof converts a string to double (then may be assigned to float). Understanding how each treats a string like "55.555" explains the different results for integer and floating additions.
Given Data / Assumptions:
- atoi("55.555") → 55 (parses leading digits only).
- atof("55.555") → 55.555.
- result1 starts at 10; result2 starts at 11.111.
- printf("%d, %f") prints the int and a floating value with six decimals.
Concept / Approach:Compute each sum separately using the conversions provided by atoi and atof.
Step-by-Step Solution:result1 = 10 + atoi("55.555") = 10 + 55 = 65.result2 = 11.111 + atof("55.555") = 11.111 + 55.555 = 66.666.printf prints the float as 66.666000 (six fractional digits by default).
Verification / Alternative check:Replacing atoi with strtol and atof with strtod yields the same numeric results for this input.
Why Other Options Are Wrong:55, 55.555: ignores the initial 10 and 11.111.66, 66.666600: integer sum is off by 1.55, 55: both values disregard conversion rules and initial values.
Common Pitfalls:Expecting atoi to round or parse decimals; confusing float print precision.
Final Answer:65, 66.666000