Home >Backend Development >C++ >Why Does Comparing Floats in C Sometimes Produce Unexpected Results?
Understanding Floating Point Comparison in C
When comparing floating point values in C , it is important to be aware of potential inaccuracies due to their limited precision. In the code snippet provided, the unexpected output "1 is right" is observed when comparing the floats a and b with constants 0.7 and 0.5, respectively.
Causes of Unexpected Output:
The issue arises because of the following reasons:
Resolution:
To obtain the expected output, you can either:
Code with Expected Output:
int main() { double a = 0.7; double b = 0.5; if (a < 0.7) { if (b < 0.5) printf("2 are right"); else printf("1 is right"); } else printf("0 are right"); }
In this corrected code, the comparison of a and b to their respective doubles ensures accurate precision, resulting in the expected output of "0 are right."
The above is the detailed content of Why Does Comparing Floats in C Sometimes Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!