having problem with a C code

Asked by sidharth

i having a problem with the following code, it's though a simple code but i am not able to understand the output given by it

#include<stdio.h>
int main()
{
     float a=0.7;

     if(a<0.700000)
          printf("Hi%f\n",a);
    else
          printf("Hello \n");
}

on compilling the above code the if statement gets true and prints "Hi", but according to me it shoul print "Hello". the condition is falls if i use "a>0.7" in if statement.

plz tell me what's the reason behind it.

Question information

Language:
English Edit question
Status:
Answered
For:
Ubuntu Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Simeon Visser (svisser) said :
#1

Floating point numbers can't reliably be compared, this has to do with the way they're represented. The precision is limited so it's not possible to represent 0.7 exactly. As a result, it's slightly less than 0.7 in this case which causes the if-statement to be true.

Revision history for this message
peter (peter-neuweiler) said :
#2

Wow - interesting. Thanks.

Revision history for this message
peter (peter-neuweiler) said :
#3

But it's strange. a is defined as float with the value 0.7. And this doesn't work? Strangel. So how can you write a c program *lol?
Peter

Can you help with this problem?

Provide an answer of your own, or ask sidharth for more information if necessary.

To post a message you must log in.