float and double

if i change the value of f and d to 10.5 it prints hi but if i give the following input it doesnt print hi,please help!

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
    float f=10.78;
    double d=10.78;
    if(f==d)
        cout<<"hi";
}
Last edited on
because if you use the type double d means 10.78345345345345345
while the float the f means 10.783453453
the compiler never know in the float f if the next digit in 3 is 9 or maybe 2 or 3 or 4
Ps: the float can hold 7 digits decimal while double can hold 15
Last edited on
then wat dooe 10.5 mean?
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
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    cout << fixed << setprecision(15);
    
    double a = 10.78;
    float  b = 10.78;
    
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    double c = 10.125;
    float  d = 10.125;
    
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;
    
    // literals
    cout << "double: "<< 10.78 << endl;
    cout << "float:  "<< 10.78f << endl;
}
a = 10.779999999999999
b = 10.779999732971191
c = 10.125000000000000
d = 10.125000000000000
double: 10.779999999999999
float:  10.779999732971191

Internally the values are stored in a binary format. A few numbers such as 1/2 or 1/4 and other powers of two can be stored accurately in floating point format. But in general, the values are approximations. double is more precise than float, so the approximation will be a bit better.

Mostly we should not test floating point values are equal. Instead, do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    cout << fixed << setprecision(15);
    
    double a = 10.78;
    float  b = 10.78;
    
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    if (abs(a - b) < 0.00001 )
        cout << "values are approximately equal" << endl;
    else
        cout << "values are not the same" << endl;
    
}
a = 10.779999999999999
b = 10.779999732971191
values are approximately equal

by the way what compiler are you using?
what compiler are you using?
in this case, MinGW GCC 4.8.1 32-bit.

As it happens, I used Orwell DevC++ as the IDE, but code::blocks is often recommended, and more or less the same compiler is available with each.

http://orwelldevcpp.blogspot.com/
http://www.codeblocks.org/
Topic archived. No new replies allowed.