top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why comparing float gives unexpected output in C?

+3 votes
883 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 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

4 Answers

+2 votes

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 by Ankush Surelia
+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 by Salil Agrawal
It's called IEEE 754 method
0 votes

Try long double, more precise than float

answer May 23, 2015 by Amit Kumar Pandey
0 votes

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
answer is less than
and when if(a==(float)5.2)
answer is equal.

answer Aug 2, 2015 by Vikram Singh
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?

0 votes

Trivial question, please help.

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

+2 votes
struct marks {
  int a:1;
  int b:2;
};

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

I am wanting to extract variable names and their size (int, char and etc.) from a c file.
Is there any way to extract that type of information?

...