consider following program:
#include<stdio.h>
int main(void)
{
float f=0.0f;
int i;
for(i=0;i<10;i++)
f=f+0.1f;
if(f==1.0f)
printf("f is equal to 1.0");
else
printf("f is not equal to 1.0");
return 0;
}
when I run above program it prints: f is not equal to 1.0
I guessed it should print f is equal to 1.0 as after coming out of for
loop its value is 1.0 only.
From the C-FAQ:
14.1: When I set a float variable to, say, 3.1, why is printf printing
it as 3.0999999?
A: Most computers use base 2 for floating-point numbers as well as
for integers. Although 0.1 is a nice, polite-looking fraction
in base 10, its base-2 representation is an infinitely-repeating
fraction (0.0001100110011...), so exact decimal fractions such
as 3.1 cannot be represented exactly in binary. Depending on
how carefully your compiler's binary/decimal conversion routines
(such as those used by printf) have been written, you may see
discrepancies when numbers not exactly representable in base 2
are assigned or read in and then printed (i.e. converted from
base 10 to base 2 and back again). See also question 14.6.
14.5: What's a good way to check for "close enough" floating-point
equality?
A: Since the absolute accuracy of floating point values varies, by
definition, with their magnitude, the best way of comparing two
floating point values is to use an accuracy threshold which is
relative to the magnitude of the numbers being compared. Rather
than
double a, b;
...
if(a == b) /* WRONG */
use something like
#include <math.h>
if(fabs(a - b) <= epsilon * fabs(a))
where epsilon is a value chosen to set the degree of "closeness"
(and where you know that a will not be zero).
References: Knuth Sec. 4.2.2 pp. 217-8.