You are here:

C/behaviour of floats

Advertisement


Question
float a=.7;
if (a==.7)
printf ("hallo");
else
printf ("bye");


the answer is "bye" ?
why 'a' is not equal to .7
                  ...thanx!


Answer
The problem is that, the float is the representation of floats.
0.7 could be 0.6999999!
So, you should not compare the floats in the traditional way.
You have to keep a precision and use it.
Here is the corrected code which you can try.

#include <stdio.h>

#define PRECISION 0.00001

main()
{
  float a = 0.7;

  if (abs(a - 0.7) <= PRECISION)
     printf("Hello\n");
  else
     printf("Bye\n");
}

This time the answer will be: "Hello".

Hope you understood the reason.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.