TOC | Prev | Next

Floats are approximations

Floats are an approximation. Because of the way they are encoded, they cannot be exact.

float-equality.c

#include <stdio.h>

int main( void ) {
    float candy_price = 0.20;
    int dozen = 12;

    float total = dozen * candy_price;

    printf( "%d candies at %3.2f each = %3.2f\n", dozen, candy_price, total );
    if ( total == 2.40 ) {
        puts( "You spent exactly 2.40" );
    }
    else {
        puts( "Strange, you didn't spend 2.40" );
    }

    return 0;
}

$ float-equality

12 candies at 0.20 each = 2.40
Strange, you didn't spend 2.40
TOC | Prev | Next