Floating literal precision comparison in C: given\n#include<stdio.h>\nint main()\n{\n float a = 0.7;\n if(a < 0.7f)\n printf("C\n");\n else\n printf("C++\n");\n return 0;\n}\nWhat will be printed (consider default promotions and literal types)?

Difficulty: Medium

Correct Answer: C++

Explanation:


Introduction / Context:
This problem explores floating-point literals, default types, and precision in C. Specifically, it contrasts assigning a double literal to a float versus using an explicit float literal for comparison.



Given Data / Assumptions:

  • float a = 0.7; // 0.7 is a double literal, then converted to float on assignment.
  • Comparison uses 0.7f, which is a float literal.
  • IEEE-754 binary floating point commonly used; 0.7 is not exactly representable.


Concept / Approach:
When assigning 0.7 (double) to a float, the value is rounded to the nearest representable float, typically about 0.699999988. The literal 0.7f is already a float with the same nearest representable value as the converted double under round-to-nearest. Thus, a and 0.7f are equal on typical systems. The test a < 0.7f is false, so the else branch executes and prints “C++”.



Step-by-Step Solution:
Store a ≈ 0.699999988 (float).Literal 0.7f ≈ 0.699999988 (same float value).Compare: a < 0.7f → false.Execute else branch → print “C++”.



Verification / Alternative check:
Print with high precision (e.g., printf("%.9f %.9f\n", a, 0.7f)) to see equal representations; or compare with == and observe true on common compilers/ABIs.



Why Other Options Are Wrong:
“C” would require a to be strictly less than 0.7f, which it is not in typical IEEE-754 float. There is no compile error, and behavior is defined for these operations.



Common Pitfalls:
Assuming decimal literals are exact; forgetting literal default types; mixing float/double without considering rounding and promotions.



Final Answer:
C++

More Questions from Floating Point Issues

Discussion & Comments

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