如预期浮点数不工作 [英] Floating point numbers do not work as expected

查看:105
本文介绍了如预期浮点数不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面当我给输入作为110 2 1 2 2,总和打印为52和sum3为31.200001了code,而它SHLD已经31.200000

  INT的main(){    INT T,N,I,A [2000]中,M,J,F;
    scanf函数(%d个,& T公司);
    而(T - ){
        scanf函数(%d个,&安培; N);
        scanf函数(%d个,&安培; F);
        对于(i = 0; I< F;我++){
            scanf函数(%d个,&安培; A []);
        }
        scanf函数(%d个,&安培; M);
        如果(N!= 0){
            INT总和= N *(N + 1)/ 2;
            INT SUM2 = 0;
            为(J = 0; J< I; J ++){
                SUM2 + = A [J]。
            }
            sum- = SUM2;
            的printf(%d个\\ N,总和);
            浮sum3;
            如果(N%2 == 0)sum3 =(1.0-2.0 * M / N)*总和;
            别的sum3 =(1.0-2.0 *米/(N + 1))*总和;
            的printf(%F \\ N,sum3);
        }
        其他的printf(0.0000 \\ n);
    }
    返回0;
}


解决方案

浮点指南:


  

为什么不是我的号码,像0.1 + 0.2加起来一个漂亮的圆0.3,
  而是我得到一个奇怪的结果,像0.30000000000000004?


  
  

由于内部,电脑使用的格式(二进制浮点)
  不能准确地重新present一个像0.1,0.2或0.3的。


  
  

当code编译或间preTED,你的0.1已经是
  圆形到该格式的最接近的数字,这导致一个小
  舍入误差的计算甚至发生之前。


In the code below when i give input as 1 10 2 1 2 2, sum is printed as 52 and sum3 as 31.200001 whereas it shld have been 31.200000

int main(){

    int t,n,i,a[2000],m,j,f;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        scanf("%d",&f);
        for(i=0;i<f;i++){
            scanf("%d",&a[i]);
        }
        scanf("%d",&m);
        if(n!=0){
            int sum=n*(n+1)/2;
            int sum2=0;
            for(j=0;j<i;j++){
                sum2+=a[j];
            }
            sum-=sum2;
            printf("%d\n",sum);
            float sum3;
            if(n%2==0) sum3=(1.0-2.0*m/n)*sum;
            else sum3=(1.0-2.0*m/(n+1))*sum;
            printf("%f\n",sum3);
        }
        else printf("0.0000\n");
    }
    return 0;
}

解决方案

From the Floating-Point Guide:

Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your "0.1" is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

这篇关于如预期浮点数不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆