gpt4 book ai didi

c - float 错误

转载 作者:太空狗 更新时间:2023-10-29 15:18:05 26 4
gpt4 key购买 nike

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com