Floating-point comparison in C: given <code>float a = 0.7;</code>, what will this program print and why? #include<stdio.h> int main() { float a = 0.7; if (0.7 > a) printf("Hi\n"); else printf("Hello\n"); return 0; }

Difficulty: Easy

Correct Answer: Hi

Explanation:


Introduction / Context:
This question examines a classic floating-point pitfall: comparing a float against a double literal. Because decimal fractions rarely have exact binary representations, the comparison may not behave as naive intuition suggests.


Given Data / Assumptions:

  • a is a float, typically ~7 decimal digits precision.
  • 0.7 is a double literal, typically ~15–16 digits precision.
  • In the comparison, a is promoted to double for evaluation.


Concept / Approach:
The binary representation of 0.7 cannot be exact. When you write float a = 0.7;, the value stored in a is the nearest representable float to 0.7, which is usually slightly less than the double literal 0.7. During comparison, a is promoted to double, preserving its slightly smaller value. Therefore, 0.7 > a typically evaluates to true, and the program prints Hi.


Step-by-Step Solution:

Store: a gets a rounded float approximation of 0.7.Promote: a → double for comparison.Compare: 0.7 (double) is slightly larger than promoted a → condition true.Output: Hi.


Verification / Alternative check:
Print with high precision: printf("%.20f %.20f\n", 0.7, (double)a); You will see the promoted a is marginally smaller than the literal.


Why Other Options Are Wrong:

Hello: would require 0.7 <= a, which is not typical.Multiple or no outputs: the code prints exactly one line.


Common Pitfalls:
Assuming decimal equality in binary floating-point; mixing float and double without awareness.


Final Answer:
Hi.

More Questions from Control Instructions

Discussion & Comments

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