  # Why comparing float gives unexpected output in C?

195 views

See the following code

``````void main(){
float a=5.2;
if(a==5.2)
printf("Equal");
else if(a<5.2)
printf("Less than");
else
printf("Greater than");
}
``````

Expected output is equal but we does not get same why? posted May 22, 2015

Use any of the below statements, it would work fine --
if ( a == (float) 5.2 )
OR
if ( a == 5.2f )

You need to inform the compiler that you are trying to compare 2 float numbers so you need to typecast it (explicit/implicit).

You can also try this --> float a= 5.2;
float b = 5.2;

Now compare them -- if (a == b ). This would also work fine answer May 25, 2015
+1 vote

Floating point numbers are never stored in the exact form, these are stored in the form of exponent and manteesa form.

``````bit  31 30    23 22                    0
S  EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
``````

now you can guess why if(a==5.2) is not equal because of they may have different value at some time :) answer Aug 3, 2015
It's called IEEE 754 method

Try long double, more precise than float answer May 23, 2015

a is float variable so it compare only float value like a=5.2 so a compare its float value i.e a=.2
.2<5.2
and when if(a==(float)5.2) answer Aug 2, 2015
Similar Questions
+1 vote

Comparing floats to Fractions gives unexpected results:

``````# Python 3.3
py> from fractions import Fraction
py> 1/3 == Fraction(1, 3)
False
``````

but:

``````py> 1/3 == float(Fraction(1, 3))
True
``````

I expected that float-to-Fraction comparisons would convert the Fraction to a float, but apparently they do the opposite: they convert the float to a Fraction:

``````py> Fraction(1/3)
Fraction(6004799503160661, 18014398509481984)
``````

Am I the only one who is surprised by this? Is there a general rule for which way numeric coercions should go when doing such comparisons?

I need to convert a string literal like "111.25" to floating point number.
atof() fails me as it returns 1111 and discards .25?

``````struct marks {
int a:1;
int b:2;
};

int main() {
struct marks obj={1,6};
printf("%d %d\n",obj.b,obj.a);
}
``````

input:
one
two
three

output:
three
two
one