c - float 错误

标签 c floating-point floating-point-conversion

#include <stdio.h>
int main()
{
    int n;
    while ( scanf( "%d", &n ) != EOF ) {
        double sum = 0,k;
        if( n > 5000000 || n<=0 )   //the judgment of the arrange
            break;
        for ( int i = 1; i <= n; i++ ) {
            k = (double) 1 / i;
            sum += k;
        }
        /*
        for ( int i = n; i > 0; i-- ) {
            k = 1 / (double)i;
            sum += k;
        }
        */
        printf("%.12lf\n", sum);
    }
    return 0;
}

为什么在不同的循环中我得到不同的答案。有 float 错误吗?当我输入 5000000总和是16.002164235299但是当我使用 for (符号部分)的另一个循环时,我得到了总和 16.002164235300 .

最佳答案

因为 floating point math is not associative :

(a + b) + c 不一定等于 a + (b + c)

关于c - float 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13453835/

相关文章:

c - 检索在 root 下运行的进程中登录的用户名或 ID

c - 这些字符串是否为 fopen() 正确连接?

java - Android:如何持久存储 float 组

在 C 中从 double(GNU 科学库)转换为 SC16Q11

javascript - 处理大数时的中点 'rounding'?

Python 中的 C# BitConverter.ToSingle 等价物

c - 在 Windows 中打印文件

c - gstreamer gst_element_seek 在 mpeg2ts 上非常慢

c++ - 当已经假设 __STDC_IEC_559__ 时,将 float 序列化为字节

c++ - 删除 float 最后一位的问题