Float value problems

When I enter two float values they will always say theyre equal or not equal based on what i entered for the two integers.

Any reason why this is happening? thanks

code below:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <cmath>
#include <cstring>

using namespace std;

int intInput1, intInput2;
float floatInput1, floatInput2;
char charInput1, charInput2;

int isEqual()
{
	if (intInput1 == intInput2)
	{
		cout << "Is equal" << endl;
		return true;
	}
	else
	{
		cout << "Not equal" << endl;
		return false;
	}

	if ((float)floatInput1 == (float)floatInput2)
	{
		printf("is equal");
		return true;
	}

	else
	{
		printf("not equal");
		return false;
	}

	if (charInput1 == charInput2)
	{
		cout << "Is equal" << endl;
		return true;
	}

	else
	{
		cout << "Not equal" << endl;
		return false;
	}
}

int main()
{
	cout << "item comparison" << endl;
	
	cout << "Please enter 2 integers" << endl;
	cin >> intInput1 >> intInput2;
	isEqual();

	cout << "Please enter 2 floats" << endl;
	cin >> floatInput1 >> floatInput2;
	isEqual();

	cout << "Please enter 2 chars" << endl;
	cin >> charInput1 >> charInput2;
	isEqual();

	cin.ignore(2);
}
Why are you trying to use the same function to test both int and floating point numbers? You should consider passing the values into your function and either overload the function for use with float, int, char or possibly create a template function.
Last edited on
Number one, you cannot accurately compare floating point values for equality. Subtract one from the other, take the absolute value, and see if the difference is less than your desired error precision.

Number two, never use float unless you have to. Always use long double or at the very least double as they are far more precise.
for float comparision use floor(floatinput1) == floor(floatinput2)
That might not always work, even if they are the same.
Topic archived. No new replies allowed.