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

Why Does Floating-Point Comparison in C Sometimes Produce Unexpected Results?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 01:21:25375browse

Why Does Floating-Point Comparison in C Sometimes Produce Unexpected Results?

Floating Point Comparison Anomalies

The concept of floating point comparisons can be misleading, especially when dealing with float data types. Consider the following example:

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");
}

Intuitively, one might assume this code would output "0 are right" since the initial condition is false. However, surprisingly, the actual output is "1 is right."

Explanation

The explanation lies in the internal representation of floating-point numbers. In C, floats are promoted to doubles during comparisons, and doubles are more precise than floats. As a result, 0.7 as a float is not exactly the same as 0.7 as a double. When 0.7 (as a float) is promoted to a double, it becomes slightly less than 0.7 (as a double).

On the other hand, 0.5 (as a float) happens to be an exact representation in double precision. Therefore, when the condition b < 0.5 is evaluated, it returns false because 0.5 (as a double) is not less than itself.

Solutions

To resolve this issue, one can either:

  1. Change float to double: By declaring a and b as doubles, you ensure that they are not promoted during comparison, and the expected behavior will be obtained.
  2. Add f suffix to literals: By appending the suffix f to the literals, you explicitly indicate that they should be treated as floats. This will prevent the promotion to doubles during comparison.

By implementing either of these solutions, you can obtain the desired output of "0 are right."

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

Statement:
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