【问题标题】:Float comparison in C [duplicate]C中的浮点比较[重复]
【发布时间】:2015-09-06 07:13:31
【问题描述】:
#include<stdio.h>
int main()
{
    float x = 0.6;
    if (x == 0.6)
        printf("IF");
    else if (x == 0.6f)
        printf("ELSE IF");
    else
        printf("ELSE");
}

此代码给出输出 ELSE IF

#include<stdio.h>
int main()
{
    float x = 0.5;
    if (x == 0.5)
        printf("IF");
    else if (x == 0.5f)
        printf("ELSE IF");
    else
        printf("ELSE");
}

此代码给出输出 IF

虽然两个程序看起来一样,但为什么输出有差异?为什么会这样?

【问题讨论】:

    标签: c if-statement compiler-errors floating-point precision


    【解决方案1】:

    因为0.5 具有 IEEE-754 二进制格式(如 binary32 和 binary64)的精确表示。 0.5 是二的负幂。另一方面,0.6 不是 2 的幂,它不能在 floatdouble 中精确表示。

    【讨论】:

    • 你刚刚知道吗?
    • @Noob 恐怕我不明白你的问题。
    • 答案非常惊人。而已 !我想知道你是怎么知道的。
    • 抱歉,我不明白你的意思。能详细点吗?
    • @AnujGarg 数字 0.50.250.125 等是 2 的负幂,因此可以在 floatdouble 中表示而不会出现表示错误。要获取有关浮点的更多信息,我建议您阅读download.oracle.com/docs/cd/E19957-01/806-3568/…
    猜你喜欢
    • 2011-10-24
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2016-05-10
    • 2015-03-19
    相关资源
    最近更新 更多