### 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:

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566`` ``````#include #include #include 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.