In the code bellow the >= and the <= operators not working well in the range of 0.04 - 2.00, but working fine otherwise. For exampple if I put in number 2 and then number 1.99 it does not print "The numbers are almost equal." as it should. What am I doing wrong? (Example from Bjarne Stroustrup/Programming)
#include "stdafx.h"
#include "D:/MyPrograms/std_lib_facilities.h"
int main()
{
double a, b;
while (cin >> a, cin >> b)
{
if (a < b)
{
cout << "The smaller value is: " << a << endl;
cout << "The larger value is: " << b << endl;
}
if (a > b)
{
cout << "The smaller value is: " << b << endl;
cout << "The larger value is: " << a << endl;
}
if (a == b)
cout << "The values are equal." << endl;
if ((a - b <= 0.01 && a - b >= -0.01) && a!=b)
cout << "The numbers are almost equal." << endl;
}
system("pause");
return 0;
}
This is a result of using floating point values. 1.99 cannot be represented using double precision (or any finite precision for that matter) so variable 2 stores closest representable number: