>= and <= operator bug?

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #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:
1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip>

int main()
{
    std::cout <<  std::setprecision(20)
              << 2.0 << '\n' << 1.99;
}
2
1.9899999999999999911
As you can see, their difference is larger than 0.01 (or should I say 0.010000000000000000208 ?)
Thank you so much!
Topic archived. No new replies allowed.