Home > Backend Development > C++ > Why Does My Floating-Point Comparison Produce Unexpected Results?

Why Does My Floating-Point Comparison Produce Unexpected Results?

Patricia Arquette
Release: 2024-12-25 02:20:09
Original
313 people have browsed it

Why Does My Floating-Point Comparison Produce Unexpected Results?

Floating Point Comparison Discrepancy

In the provided code snippet:

int main()
{
    float a = 0.7;
    float 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");
}
Copy after login

the expected output of "0 are right" is not obtained. Instead, "1 is right" is printed. This discrepancy arises due to the inherent imprecision of floating-point numbers.

When performing comparisons with floating-point operands, they are automatically promoted to double-precision values. Floats, being less precise than doubles, may not represent the intended value exactly. In this case, when a (a float) is compared to 0.7 (a double), a is internally converted to a double and loses precision. This results in a being slightly less than 0.7, causing the a < 0.7 comparison to evaluate to true.

To resolve this issue, one can either:

  • Change float to double:
double a = 0.7;
double b = 0.5;
Copy after login
  • Use float literals with an 'f' suffix:
float a = 0.7f;
float b = 0.5f;
Copy after login

Both approaches ensure that the operands remain as floats and avoid the precision loss during promotion to double.

The above is the detailed content of Why Does My Floating-Point Comparison Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template