C compiler error (floating point arithmetic)?

#include<stdio.h>

int main()
{
    double fract=0;
    int tmp;

    //scanf("%lf",&fract);
    fract=0.312;
    printf("%lf",fract);
    printf("\n\n");
    while(fract>0){
        fract*=(double)10;
        printf("%d ",(int)fract);
        fract-=(int)fract;
    }
    getch();
    return 0;
}

      

this shoud code has output: 312

but somehing doesn't fit. I am using devcpp 4.9.9.2 compiler ...

0


source to share


3 answers


Kernighan and Plager say in their old but classic book , Elements of a Programming Style , that:

  • A moderate old programmer once said that "floating point numbers are like little piles of sand, every time you move one you lose some sand and you get some dirt."

They also say:



  • 10 * 0.1 hardly ever 1.0

Both statements indicate that floating point arithmetic is not accurate.

Note that some modern processors (IBM PPCs) have built-in IEEE 754: 2008 floating point arithmetic. If you use the correct types, your calculations will be accurate.

+12


source


Floating point arithmetic is confusing and not guaranteed to behave intuitively.

Here's a good reference document: What Every Computer Scientist Should Know About Floating Point Arithmetic . This is a long document because it is a complex issue.



In short: don't use floating point values ​​if you rely on exact values.

+6


source


So you multiplied 0.3119999999999999999895916591441391574335284531116485595703125 by 1000 and truncated it to get 311? I can't see where the problem is.

+6


source







All Articles