双浮法比较 [英] double and float comparison

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

问题描述

根据这篇文章,当比较一个浮点和一个双,浮点应该被视为双。
下面的程序,似乎不遵循这个语句。这种行为看起来很不可预测。
这是我的程序:

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时,会显示成功。

  • 我也打印了十六进制的值的值。它们在两种情况下都不同。我的编译器是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天全站免登陆