计算中

123456789 (1 110 1011 0111 1001 1010 0010 101) 
      +20 (                            10 100)

C中的结果是123456816(1 110 1011 0111 1001 1010 0110 000)我发现它似乎是四舍五入的,但在计算中

123456785 (1 110 1011 0111 1001 1010 0010 001)
      +20 (                            10 100) 

(结果是123456800)在这一点上,它看起来像是四舍五入,而两者加在一起看起来像是四舍五入

123456809 (1 110 1011 0111 1001 1010 0101 001) 

再说一次,123456808 (1 110 1011 0111 1001 1010 0101 000)没有意义

I tried to find the answer on Google and summed up the netizens' opinions were rounded nearby, 但 it still did not match the above results, so I think there may be some details I do not know, so I hope you can help me to figure out this problem


添加代码以演示:

#include <stdio.h>

int main(void) {
    float x = 123456789.f;
    float y = 20.f;
    
    long m = 123456789L;
    long n = 20L;
    
    printf("As Floats, sum is: %0.1f\n", x+y);
    printf("As Longs,  sum is: %ld\n", m + n);
    
    return 0;
}

输出

As Floats, sum is: 123456816.0
As Longs,  sum is: 123456809

推荐答案

代码不包含123,456,789和20的浮点加法.它包含123,456,792和20的加法.有多个步骤(以下使用通常用于float的格式,IEEE-754二进制32,具有24位有效数):

  • float x = 123456789.f;中,数字123456789.被转换为float.转换的结果是最接近的可表示值,123,456,792,相当于+15,432,099统计23.请注意,在这种形式中,有效数15,432,099适合24位.(The next lower representable value is +15,432,098·2
  • float y = 20.f;中,数字20.被转换为float.转换的结果是最接近的可表示值20.
  • x+y中,两个float值相加,因此我们将123,456,792和20相加.使用实数算术得到的结果将是+15,432,099·23+20=+15,432,float.5·23.然而,15,432,float.5需要25位,因此它不适合float格式.最接近的两个可表示有效数是15,432,float和15,432,float.它们的距离一样近,规则是使用偶数位数的那个.因此结果是+15,432,float·23=123,456,816.

C++相关问答推荐

Bison解析器转移/减少冲突

如何判断宏参数是否为C语言中的整型文字

在C语言中使用scanf()时我无法理解的警告

手动矢量化性能差异较大

如何将已分配的数组(运行时已知的大小)放入 struct 中?

Win32API Wizzard97 PropSheet_SetWizButton不工作

&;(str[i])和(&;str)[i]有什么区别?

在创建动态泛型数组时,通过realloc对故障进行分段

如何计算打印二叉搜索树时每行所需的空间?

无法在OpenGL上绘制三角形

使用nmake for程序比Hello World稍微复杂一些

C11/C17标准允许编译器清除复合文字内存吗?

我不知道为什么它不能正常工作,我用了get()和fget(),结果是一样的

生成的头文件不包括用户定义的文件

分配给静态变量和动态变量的位置之间有区别吗?

如何在Rust中处理C的longjmp情况?

C 语言中 CORDIC 对数的问题

const struct 成员的 typedef 中的灵活数组大小

添加/删除链表中的第一个元素

使用邻接表创建图