Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c - Floating point numbers do not work as expected

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
",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
",sum3);
        }
        else printf("0.0000
");
    }
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...