Problem in "if" function

Another stupid newby question :(

I wrote this programm, and the "if (check==height)" in the "while" sequence doesn't work (it's never true). The problem might be that "hight" and "check" are "float". I did check exactly the same programm for "int", and in works just fine.


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
#include <iostream>
#include <fstream>

using namespace std;

main()
{
    float height, check;
    short counter=0;
    ifstream input("D:\\Studies\\C++\\projects\\input.txt");
    ofstream output("D:\\Studies\\C++\\projects\\output.txt");
    output<<"The information been read from input file \n"<<"Height          Frequency \n";
    for (check=1.3; check<=2.2; check+=0.01, counter=0)
    {
        while ( !input.eof() )
        {
            input>>height;
            if (check==height)
             counter++;
        }
        if (counter>0)
         output<<" "<<check<<"               "<<counter<<"\n";
        input.clear();
        input.seekg(0);
    }
}
Last edited on
Seems you are comparing floats for (in)equality. Never, ever do this. Floats are by nature not precisely represented. Use integers instead, or compare using epsilon.

E.g.
 
if (fabs(height - check) <= (fabs(height) + fabs(check)) * 0.0001) ...
I was required to use floats and didn't know that I can't compare them, used "if (fabs(check-hight) < 0.001)" and it worked just fine, thank you so much.
Topic archived. No new replies allowed.