双倍和浮动比较 [英] double and float comparison

查看:138
本文介绍了双倍和浮动比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这篇文章,当比较一个浮点和一个double,float应该被视为double。
以下程序似乎没有遵循此语句。行为看起来相当不可预测。
这是我的程序:

According to this post, when comparing a float and a double, the float should be treated as double. The following program, does not seem to follow this statement. The behaviour looks quite unpredictable. Here is my program:

void main(void)
{
    double a = 1.1;  // 1.5
    float b = 1.1;   // 1.5
    printf("%X  %X\n", a, b);
    if ( a == b)
        cout << "success " <<endl;
    else
        cout << "fail" <<endl;
}




  • 当我运行以下程序时,我得到失败显示。

  • 但是,当我将a和b更改为1.5时,显示success。

  • 我还打印了值的十六进制符号。在这两种情况下,它们是不同的。我的编译器是Visual Studio 2005

    I have also printed the hex notations of the values. They are different in both the cases. My compiler is Visual Studio 2005

    你可以解释这个输出吗?谢谢。

    Can you explain this output ? Thanks.

    推荐答案

    float f = 1.1;
    double d = 1.1;
    if (f == d)
    

    在此比较中, f 被提升为键入 double 。你所看到的问题不在于比较,而是在初始化中。 1.1 无法正确表示为浮点值,因此存储在 f d 是可以表示的最接近的值。但是, float double 是不同的大小,所以有不同数量的有效位。当 f 中的值被提升为 double 时,没有办法收回丢失的额外位值被存储,所以你最终得到所有零的额外的位。这些零位与 d 中的位不匹配,因此比较为false。而比较成功的原因是 1.5 1.5 可以表示为 float double ;它的低位有一堆零,所以当促销增加零时,结果与 double 表示相同。

    In this comparison, the value of f is promoted to type double. The problem you're seeing isn't in the comparison, but in the initialization. 1.1 can't be represented exactly as a floating-point value, so the values stored in f and d are the nearest value that can be represented. But float and double are different sizes, so have a different number of significant bits. When the value in f is promoted to double, there's no way to get back the extra bits that were lost when the value was stored, so you end up with all zeros in the extra bits. Those zero bits don't match the bits in d, so the comparison is false. And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.

    这篇关于双倍和浮动比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆