comparison between 0.7 and float f = 0.7

The following program prints hi while logically it should print hello, I can't understand the problem

1
2
3
4
 float a = 0.7;
    if(0.7 > a)
        printf("hi");
    else printf("hello");
Its because the number 0.7 is a double, not a float, so the computer gets confused. Instead of 0.7, put 0.7f, which is a float, and it should work
So why does the comparison fail if 0.7 is double?
I just tried debugging it then, and it seems that:
a = 0.699999988
and in the if statement, it compares:
0.6999999999996 > 0.699999988 (a)
I don't know exactly why this happens though but its just because its converting between double and float incorrectly I think
because its converting between double and float incorrectly I think

No, that's not the reason.

It's because both double and float store the value in binary, rather than decimal.
In neither case is it possible to exactly represent the decimal value 0.7 in binary. So we have two approximations to the actual value, the double is more precise, and therefore different to the float.
Perhaps the following will shed some light:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <limits>
#include <iomanip>

template <typename T>
unsigned get_max_precision()
{
    return std::numeric_limits<T>::max_digits10 + 1;
}

int main()
{
    float   a = 0.7;
    double  b = 0.7;

    std::cout << std::setprecision(get_max_precision<double>());
    std::cout << "a is " << a << "\nb is " << b << '\n';
}


http://ideone.com/1bnsbG
Last edited on
Topic archived. No new replies allowed.