float

according to me the output should be hi.y is it not so?

1
2
3
4
5
6
7
8
9
10
11
 #include <iostream>
using namespace std;
int main()
{
    float a=5.2;
    if(a==5.2)
        cout<<"hi";
    else if(a<5.2)
        cout<<"bye";
    else cout<<"war";
}
5.2 is a double value, so I would make line 5 be double a = 5.2;. It should say "hi" then.

The other option is to do this, which should also make it print "hi".
1
2
3
    float a=5.2f;
    if(a==5.2f)
        cout<<"hi";
This makes it a float from the start, instead of having to implicitly go from a double to a float, thereby losing precision.

------------

Directly comparing equality between two floats is error-prone due the inexact nature of the representation. If you had to do addition/subtract/etc to a variable before testing for equality, you could get round-off errors, and I would compare two float values against a threshold.
ex:
1
2
if (a >  5.2-0.0001 && a < 5.2+0.0001)
    cout << "a is close enough to 5.2" << endl;
Last edited on
Topic archived. No new replies allowed.