3

Possible Duplicate:
Floating point comparison

When I run the code below I get the following output:

Output : if

Why does this happen?

#include <stdio.h>

void main()
{
    float a = 0.7;
    if(a<0.7)
    {
        printf("if");
    }
    else
    {
        printf("Else");
    }
}
Community
  • 1
  • 1
sam_k
  • 5,983
  • 14
  • 76
  • 110
  • 6
    [What every programmer should know about floating-point arithmetic](http://floating-point-gui.de/) – Bart Oct 31 '11 at 08:18
  • @downvoter dont be panic just by asking same question by new user ...close such questan as duplicate but dont downvote it – Jeegar Patel Oct 31 '11 at 08:26
  • This an applet which illustrates the internal working a bit better: http://www.h-schmidt.net/FloatApplet/IEEE754.html – ChrisWue Oct 31 '11 at 08:28

3 Answers3

3

Your program compares the double representation of 0.7 (which is what the compiler produces when you write 0.7 in your program) with a float representation of 0.7 (which is what variable a contains). The two are not the same, and it just happens that the double one is slightly larger.

EDIT: (float)0.7 can be represented compactly in hexadecimal notation. It is 0x1.666666p-1. 0.7 as a double constant is 0x1.6666666666666p-1, so it is slightly larger.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
2

Floating points are not stored in precise format. Most likely, your platform interprets

float a = 0.7;

as

float a = 0.69999....;

This is because of the internal representation of floating points on your platform. The link provided by Daniel should get you started.

Williham Totland
  • 28,471
  • 6
  • 52
  • 68
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

That is due to accuracy issues in floating point representation on a computer. See this Wikipedia article.

Daniel Rose
  • 17,233
  • 9
  • 65
  • 88