比较C中的float和double [英] Comparing float and double in C

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

问题描述

我编写了以下代码,以比较C中的float变量和double变量.

I wrote the following code to compare between a float variable and a double variable in C.

int main()
{
    float f = 1.1;
    double d = 1.1;

    if(f==d)
        printf("EQUAL");

    if(f < d)
        printf("LESS");

    if(f > d)
        printf("GREATER");

    return 0;
}

我正在使用在线C编译器此处来编译我的代码.

I am using an online C compiler here to compile my code.

我知道,对于重复的小数,将永远不会打印EQUAL.但是,我期望应该打印的是LESS,因为double应该具有更高的精度,因此应该比float更接近1.1的实际值.据我所知,在C中,当您比较float和double时,float的尾数会零扩展为double,并且零扩展的值应始终较小.

I know that EQUAL will never be printed for recurring decimals. However what I expect should be printed is LESS since double should have a higher precision and therefore should be closer to the actual value of 1.1 than float is. As far as I know, in C when you compare float and double, the mantissa of the float is zero-extended to double, and that zero-extended value should always be smaller.

在所有情况下都将打印GREATER.我在这里想念什么吗?

Instead in all situations GREATER is being printed. Am I missing something here?

推荐答案

最接近1.1的浮点数的确切值为1.10000002384185791015625.二进制等效项为1.00011001100110011001101

The exact value of the closest float to 1.1 is 1.10000002384185791015625. The binary equivalent is 1.00011001100110011001101

最接近于1.1的double的精确值是1.100000000000000088817841970012523233890533447265625.二进制等效项是1.0001100110011001100110011001100110011001100110011010.

The exact value of the closest double to 1.1 is 1.100000000000000088817841970012523233890533447265625. The binary equivalent is 1.0001100110011001100110011001100110011001100110011010.

将两个二进制数字紧挨在一起:

Lining up the two binary numbers next to each other:

1.00011001100110011001101
1.0001100110011001100110011001100110011001100110011010

要舍入为浮点数的前几个截断位是11001100,大于一半,因此将转换为浮点数舍入,使其最低有效位为11001101.舍入导致最大有效差为1.在双精度位为0的位中.浮点数大于双精度数,无论低有效位的值在扩展为双精度的浮点数中为零,还是在双精度数中不为零.

The first few truncated bits for rounding to float are 11001100, which is greater than half, so the conversion to float rounded up, making its least significant bits 11001101. That rounding resulted in the most significant difference being a 1 in the float in a bit position that is 0 in the double. The float is greater than the double, regardless of values of bits of lower significance being zero in the float extended to double, but non-zero in the double.

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

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