C 具有基本整数值的 float 给出不同的结果

标签 c floating-point

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

但是在最简单的赋值中,例如 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(如 0.00123),我可以理解它,但它只是直接使用整数来找出 float 的限制。

最佳答案


    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

关于C 具有基本整数值的 float 给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53620981/

相关文章:

c++ - libcurl SMTP 读取函数返回有趣的值段错误 C++

actionscript-3 - 如何在没有精度错误的情况下正确划分微小的 double 字?

c - 舍入错误 : The Sum

c - 我的自定义 shell 程序仅重定向一行

c - shmat() 失败,返回 "Identifier removed"

c - 通过管道读写数据

c - 这个 C 习语是什么意思?

c - 将 char 指针分配给 char 和 char 数组变量

python - 从 str 转换为 float 时保持尾随 0

java - Java中 float 的最大值?