I am working on a calculation which is to convert double to binary, a strange problem happens during this process and finally leads to an error. So I print out the fractional part when I found result is wrong.
A piece of code for fractional part is like this:
        while(float_part != (int)(float_part)){
            float_part -= (int)(float_part); //just leave fractional part
            float_part *= 2; //float_part is a double
            res = res + to_string(((int)(float_part))); //add to "res", which is a string
            cout << float_part << "+" << length << "\n"; //to figure out why
            length--;  //the length is initialized to 32
            if(length <= 0){
                return "ERROR"; //if too long
            }
    }
Then I input "28187281.525"(only .525 matters in the above piece of code) and found the result is so weird:
    1.05+32
    0.1+31
    0.2+30
    0.4+29
    0.8+28
    1.6+27
    1.2+26
    0.4+25
    0.799999+24
    1.6+23
    1.2+22
    0.399994+21
    0.799988+20
    1.59998+19
    1.19995+18
    0.399902+17
    0.799805+16
    1.59961+15
    1.19922+14
    0.398438+13
    0.796875+12
    1.59375+11
    1.1875+10
    0.375+9
    0.75+8
    1.5+7
    1+6
    1101011100001101010010001.100001100110011001100110011
In the beginning it's okay, but eventually the result becomes wrong!
And why 0.4*2 become 0.799999..
Anyone know the reason? Thanks in advance!
 
     
     
    