logic error or problem with if stmt ?

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Aug 2007
Posts: 2
Reputation: npd_ddit is an unknown quantity at this point 
Solved Threads: 0
npd_ddit npd_ddit is offline Offline
Newbie Poster

logic error or problem with if stmt ?

 
0
  #1
Jul 13th, 2009
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??
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 14
Reputation: mrinal.s2008 is an unknown quantity at this point 
Solved Threads: 0
mrinal.s2008's Avatar
mrinal.s2008 mrinal.s2008 is offline Offline
Newbie Poster

Re: logic error or problem with if stmt ?

 
0
  #2
Jul 13th, 2009
change your if condition as below
  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.
Reply With Quote Quick reply to this message  
Join Date: Dec 2007
Posts: 442
Reputation: Agni is a jewel in the rough Agni is a jewel in the rough Agni is a jewel in the rough 
Solved Threads: 68
Sponsor
Agni's Avatar
Agni Agni is offline Offline
Posting Pro in Training

Re: logic error or problem with if stmt ?

 
1
  #3
Jul 13th, 2009
This thread here talks about float comparisons. There's a good link available in the thread about the same.

Thread1
thanks
-chandra
Reply With Quote Quick reply to this message  
Join Date: Aug 2007
Posts: 2
Reputation: npd_ddit is an unknown quantity at this point 
Solved Threads: 0
npd_ddit npd_ddit is offline Offline
Newbie Poster

Re: logic error or problem with if stmt ?

 
0
  #4
Jul 14th, 2009
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.

Originally Posted by mrinal.s2008 View Post
change your if condition as below
  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.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC