In C programming, consider floating-point comparison: #include<stdio.h> int main() { float a = 0.7; if (a < 0.7) printf("C "); else printf("C++ "); return 0; } What will be printed, given typical binary floating-point representation and usual type promotions during comparison?

Difficulty: Medium

Correct Answer: C

Explanation:

Introduction / Context:This question tests understanding of binary floating-point representation, literal types, and the usual arithmetic conversions that occur in comparisons in C. Small decimal fractions like 0.7 cannot be represented exactly in binary IEEE-754 format, which leads to subtle comparison results.

Given Data / Assumptions:

  • Variable a is declared as float and initialized with the decimal literal 0.7.
  • The literal 0.7 has type double in C unless suffixed; thus the expression a < 0.7 promotes a to double before the comparison.
  • printf prints either "C" or "C++" followed by a newline.

Concept / Approach:Binary floating-point cannot exactly encode most decimal fractions. The float value stored in a is typically slightly less than 0.7 when rounded to 24-bit float precision. During the comparison, a is promoted to double and compared with the double literal 0.7, which is represented with about 53 bits of precision and is slightly different from the rounded float value.

Step-by-Step Solution:Store a = (float)0.7 → value becomes approximately 0.69999999...Compare as double: (double)a ≈ 0.69999999... versus 0.7 (double).Since 0.69999999... < 0.7 is true, the if branch executes.printf prints "C".

Verification / Alternative check:If we force both sides to float (e.g., compare a with 0.7f), many compilers still yield a slightly smaller value for a than 0.7f; result remains true. If we assign double a2 = 0.7 and compare a2 < 0.7, the result is false.

Why Other Options Are Wrong:C++: would require a to be ≥ 0.7, which is not the case with typical float rounding.Compiler error: the program is valid standard C.None of the above: not applicable since "C" matches the behavior.

Common Pitfalls:Assuming decimal literals are exact; forgetting that 0.7 is double; assuming float values compare equal to their decimal literals.

Final Answer:C

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion