I was struck by this strange behavior:
float pi = 3.14;
if(pi == 3.14)
cout << "OK";
else
cout << "How is it possible?";
Could anyone explain this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The constant in the
ifstatement is(double)3.14. It is very close to itsfloatversion, but not exactly equals it, because3.14is not represented exactly.Try the same trick with
1.25or any other number that can be represented exactly, and you will get anOK.You could also cast
3.14tofloatto get anOK: