lundi 22 février 2021

Problem with count the decimal part by C++?

I'm a newbie in C++. I got trouble when count the decimal part by C++, here is the example and code:

example:

   3.01: count of decimal part is 2
103.939: count of decimal part is 3

code:

int result = 0;
double d   = 4.01;

while(true) {
    cout << "(int)d: " << (int)d << endl;
    if(d == (int)d) break;

    d *= 10;
    cout << "d *= 10: " << d << endl;

    result++;
}
cout << result << endl;

console:

int(d): 4
d *= 10: 40.1
int(d): 40
d *= 401
int(d): 400
d *= 10: 4010
int(d): 4009
...

what happens to 4.01? And the same strange result when the double = 5.01 etc. I know it's the problem of precision when convert DOUBLE to INT, but I'm really curious about how it happens when the test doubles like 4.01, 5.01, etc.

And in addition, how to modify the if state correct to test 4.01?

Aucun commentaire:

Enregistrer un commentaire