0
#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 code shoud have an output of: 312

but somehing isn't going right.. i'm using devcpp 4.9.9.2 compiler...

abelenky
  • 61,055
  • 22
  • 102
  • 154
prinzrainer
  • 199
  • 1
  • 5
  • 12

3 Answers3

12

Kernighan & Plauger say, in their old but classic book "The Elements of Programming Style", that:

  • A wise old programmer once said "floating point numbers are like little piles of sand; every time you move one, you lose a little sand and gain a little dirt".

They also say:

  • 10 * 0.1 is hardly ever 1.0

Both sayings point out that floating point arithmetic is not precise.

Note that some modern CPUs (IBM PPC) have IEEE 754:2008 decimal floating point arithmetic built-in. If using the correct types, then your calculation will be exact.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
  • 1
    Well, in its way floating point arithmetic is precise, what is not so precise is converting floating point's typical base 2 mantissas to base 10 values. – ninjalj Oct 23 '10 at 11:40
6

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. It's a long document, because it's a complicated problem.

In summary: Don't use floating-point values if you are relying on exact values.

John Calsbeek
  • 35,189
  • 7
  • 91
  • 100
6

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

R.. GitHub STOP HELPING ICE
  • 201,833
  • 32
  • 354
  • 689