0

Today I was playing with floating-point number in C
code likes:

float a = 0.0;
a += 0.8;
if(a == 0.800000)
   printf("correct");

The if statement do not get executed and for this I printed the value of a which was 0.800000.

void main(){

    float a=0.0f;

    a=a+0.1f;


    if(a==0.1f) 
    printf( "1correct");

    a += 0.1f;

    if(a==0.2f) 
    printf( "2correct");

    a += 0.1f;

    if(a==0.3f) 
    printf( "3correct");

    a += 0.1f;

    if(a==0.4f) 
    printf( "4correct");

    if(a==0.5f) 
    printf( "5correct");

    a += 0.1f;

    if(a==0.6f) 
    printf( "6correct");


    a += 0.1f;

    if(a==0.7f) 
    printf( "7correct");


    a += 0.1f;


    if(a==0.8f) 
    printf( "8correct");

} 

The following program prints output as :

1correct2correct3correct4correct5correct6correct

the statement 7correct and 8correct are not being printed out.

Any one please can explain Brief here!!

Asis
  • 683
  • 3
  • 23

2 Answers2

-1

Because floating-point numbers can lose in precision because of maximum error value, you must check for a small range and not equality.

Take a look here and here for more.

Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
-1

There are many decimal numbers that cannot be precisely represented with a finite number of binary digits.

In general, it's a bad idea to test floats or doubles for exact equality. If you really want to test them, check that they fit within a small range:

if ( a > 0.799999 && a < 0.800001 )
    printf( "correct" );

Whenever you can possibly use integers rather than floats or doubles, do so. For example don't use a float for a loop counter or array index.

There are lots of good uses for floating point, such as modeling physical phenomena, predicting the weather and so on, but floating point has many subtleties.

Mike Crawford
  • 2,232
  • 2
  • 18
  • 28