943,542 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 480
  • C++ RSS
Jul 13th, 2009
0

logic error or problem with if stmt ?

Expand Post »
main()
{
float a=0.7;
if(a<0.7) cout<<"true" ;else cout<<"false";
}
problem---> it prints true .....
when 0.7 is replaced everywhere with 0.8 it displays false
again with 0.9 , it displays true..
typically only for 0.7 and 0.9 it gives different answer ,then the conventional logical answer..why so??
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
npd_ddit is offline Offline
2 posts
since Aug 2007
Jul 13th, 2009
0

Re: logic error or problem with if stmt ?

change your if condition as below
c++ Syntax (Toggle Plain Text)
  1. if(a < 0.7f)

I do not remember the exact reason for the behavior in your code, it has got something to do with how floats are treated by the hardware.
Someone please elaborate.
Reputation Points: 10
Solved Threads: 1
Light Poster
mrinal.s2008 is offline Offline
28 posts
since Dec 2008
Jul 13th, 2009
1

Re: logic error or problem with if stmt ?

This thread here talks about float comparisons. There's a good link available in the thread about the same.

Thread1
Featured Poster
Reputation Points: 431
Solved Threads: 116
Practically a Master Poster
Agni is offline Offline
654 posts
since Dec 2007
Jul 14th, 2009
0

Re: logic error or problem with if stmt ?

thank you mrinal..
i think it is because the default datatype is double ..hence to do a proper comparison of float values,we have to specify it .
thanks.

change your if condition as below
c++ Syntax (Toggle Plain Text)
  1. if(a < 0.7f)

I do not remember the exact reason for the behavior in your code, it has got something to do with how floats are treated by the hardware.
Someone please elaborate.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
npd_ddit is offline Offline
2 posts
since Aug 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Help with Arrays
Next Thread in C++ Forum Timeline: Program help...





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC