Stroustrup PPP Ch 4 drill

I can't figure out what's going wrong, the if statement seems to work randomly.
The first part of drill is a while loop that reads two numbers, prints out which is smaller and larger, and if equal says they're equal. And now I have to make it write out "the numbers are almost equal" if the two numbers differ by less than 1.0/100. When I try 1 and 1.01, it correctly doesn't output "the numbers are almost equal", but when I try 2 and 2.01, it does. Those should have the same difference...so I don't know what's going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
double num1;
double num2;
while (cin >> num1 >> num2) {
	if (num1 < num2) {
		cout << "the smaller value is: " << num1 << endl;
		cout << "the larger value is: " << num2 << endl;
		if (num2 - num1 < (1.0/100)) {
			cout << "the numbers are almost equal" << endl;
		}
	}
	else if (num2 < num1) {
		cout << "the smaller value is: " << num2 << endl;
		cout << "the larger value is: " << num1 << endl;
		if (num1 - num2 < (1.0/100)) {
			cout << "the numbers are almost equal" << endl;
		}
	}
	else if (num1 == num2) {
		cout << "the numbers are equal" << endl;
	}
}
1.01 and 2.01 cannot be exactly represented in binary, so they will be rounded. One of them rounds slightly up, second down.
I had used following to look into it:
1
2
3
4
5
6
7
8
9
10
#include <iomanip>
//...
if (num1 < num2) {
    std::cout << std::setprecision(20);
    std::cout << "the smaller value is: " << num1 << std::endl;
    std::cout << "the larger value is: " << num2 << std::endl;
    std::cout << num2 - num1 << std::endl;
    if (num2 - num1 < (1.0/100))
        std::cout << "the numbers are almost equal" << std::endl;
}
1 1.01
the smaller value is: 1
the larger value is: 1.0100000000000000089
0.010000000000000008882
2 2.01
the smaller value is: 2
the larger value is: 2.0099999999999997868
0.0099999999999997868372
the numbers are almost equal
https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
Last edited on
Topic archived. No new replies allowed.