繁体   English   中英

带有基本整数值的 C Float 会给出不同的结果

[英]C Float with a basic integer value giving different results

好的,我有一个简单的问题。 在我的冒险中,我寻求数据类型中可以容纳的最大数字,并且我正在尝试诸如 long int 、doubles 和 floats 之类的东西。

但是在最简单的分配中,例如 Float x = 12345789 ,它给了我 123456792 作为输出。 这是代码

#include <stdio.h>


int main()
{
 int x = 1234567891 ;
long int y = 9034567891234567899;
long long int  z = 9034567891234567891;
float t = 123456789 ;
printf("%i \n%li \n%lli \n%f \n ",x,y,z,t);
}

我得到的输出是

1234567891
9034567891234567899
9034567891234567891
123456792.000000

我在 linux 上编码并使用 gcc。 可能是什么问题呢 ?

为清楚起见,如果您提供更高的数字,例如

float t = 123456789123456789

它将获得前 9 个正确但在不应该的最后一个数字中进行某种四舍五入。

1234567890519087104.000000

如果我像 0.00123 这样的超过 0 的工作,我可以理解它,但它只是直接使用整数来找出浮点数的限制。


    Value:                          123456789
    Hexadecimal representation:     0x4ceb79a3
    Binary representation:          01001100111010110111100110100011
                                    sign    (0)                      : +1
                                    exponent(10011001)               : 2^26
                                    mantissa(11010110111100110100011): 1.8396495580673218
    Value actually stored in float: 1.8396495580673218 * 2^26 = 123456792
    Error due to conversion:        3 

float_converter_image


int main()
{
    float t = 123456789;
}

main:
        push    rbp
        mov     rbp, rsp
        movss   xmm0, DWORD PTR .LC0[rip]
        movss   DWORD PTR [rbp-4], xmm0
        mov     eax, 0
        pop     rbp
        ret
.LC0:
        .long   1290500515     //(0x4CEB79A3)

compiler_explorer_image

  • 为了您寻求每种数据类型的最大数量的冒险,我想您可以探索标准头文件,例如float.hlimits.h

要找到可以从整数到浮点数再到整数往返的最大连续整数值,可以使用以下实验:

#include <stdio.h>

int main()
{
    long i = 0 ;
    float fint = 0 ;

    while( i == (long)fint )
    {
        i++ ;
        fint = (float)i ;
    }

    printf( "Largest integer representable exactly by float = %ld\n", i - 1 ) ;

    return 0;
}

然而,该实验在很大程度上是不必要的,因为该值是可预测的 2 24,因为 23 是浮点尾数中的位数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM