比较float和double [英] Comparing float and double

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

问题描述

#include <stdio.h>
int main(void){
    float a = 1.1;
    double b = 1.1;
    if(a == b){
        printf("if block");
    }
    else{
        printf("else block");
    }
    return 0;
}

打印:else块

Prints: else block

#include <stdio.h>
int main(void){
    float a = 1.5;
    double b = 1.5;
    if(a == b){
        printf("if block");
    }
    else{
        printf("else block");
    }
    return 0;
}

打印:如果块

这背后逻辑?

编译器使用:GCC-4.3.4

Compiler used: gcc-4.3.4

推荐答案

这是因为 1.1 是二进制浮点不完全重新presentable。但 1.5

This is because 1.1 is not exactly representable in binary floating-point. But 1.5 is.

其结果是,在浮动双击重新presentations将持有<$略有不同的值C $ C> 1.1 。

As a result, the float and double representations will hold slightly different values of 1.1.

下面是什么时候作为二进制浮点写出的区别是:

Here is exactly the difference when written out as binary floating-point:

(float) 1.1 = (0.00011001100110011001101)₂
(double)1.1 = (0.0001100110011001100110011001100110011001100110011010)₂

因此​​,当你对它们进行比较(与浮动版本被提升),他们不会是平等的。

Thus, when you compare them (and the float version gets promoted), they will not be equal.

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

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