Need help with checking if two numbers are almost equal

Hello,
I need to make a program that says if 2 numbers are almost equal (if they differ by 0.1) and i have no clue at all how to do this!

This is the code right now that i need to add the function to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 int main()
{
	double v1;
	double v2;
	cout << "Please enter 2 numbers: " ;
	while (cin >> v1 >> v2) {

	if (v1 < v2)
cout << "The smaller number is: " << v1 << "\nThe larger number is: " << v2;
		
		if (v2 < v1)
cout << "The smaller number is: " << v2 << "\nThe larger number is: " << v1;
		
		if (v1 == v2)
cout << "The numbers are equal!";
	}
}	

Please help! (and sorry if my english suck i'm from denmark :) )
Last edited on
if two numbers are no more that 0.1 apart, then absolute value of their difference is no larger that 0.1

So you need to check if |a - b| <= 0.1
This function will be helpful: http://www.cplusplus.com/reference/cmath/fabs/
Thank you! :)

I wrote: if (a - b == 0.1)
instead of (a - b <= 0.1)
You have made some mistakes:
1) ideally 0.9 will be almost equal to 0.8, but 0.8 will not be almost equal to 0.9
2) 0.9 will not be almost equal to 0.899
3) I said ideally, because comparing floating point value with == or != should be avoided. Floating point number are inprecise, and this can lead to undesired effects. In some condition (cos(x) != cos(x)) will evaluate to true!
Topic archived. No new replies allowed.