LearnFrenzy
Sign in Take a free test

Decision Making · Predict the Output · Question 8

Exact vs tolerant comparison of doubles in a condition Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following C program?

main.c
#include <math.h>
#include <stdio.h>

int main(void) {
    double a = 0.1 * 3, b = 0.3;
    printf("%s, %s\n", a == b ? "equal" : "not equal", fabs(a - b) < 1e-9 ? "close" : "far");
    return 0;
}
  • A not equal, close Correct
  • B equal, close
  • C not equal, far
  • D equal, far
Correct Answer: Option A

0.1 × 3 is 0.30000000000000004 in binary floating point, so exact equality fails – but the difference is about 5 × 10⁻¹⁷, well inside the tolerance.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links