Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Basically im trying to enter a value into the console, and output the decimal point as a whole number, and thats what needs to essentially occur.

I've developed a way to do this, using float, int and simple maths. I'm still new to C++ but this error is not making sense.

If you enter 0.01, 0.02, 0.03, 0.04, 0.06 or 0.08 you get the wrong output. I basically want to make it as simple as 0.06 * 100 = 6.

I'm pretty sure its a simple mistake, but why is this so, when clearly I'm entering a whole float number anyway.

#include <iostream>
using namespace std;

int main()
{
    float input = 0;

    while (input <= 0 || input > 999.99)
    {
        cout << "Please enter a number with decimal: ";
        cin >> input;
    }

    int whole_num = input;
    float to_decimal = input - whole_num;
    int decimal = to_decimal * 100;

    cout << decimal << endl;

    return 0;
}

EDIT: I found the solution for my problem


There was a problem with the float accuracy. So far adding 0.5f to the int can fix the problem. I know it does it properly to input of 2 decimal places, not sure for other types.

Thanks to Frederik Slijkerman!

#include <iostream>
using namespace std;

int main ()
{
float asfloat = 0.03;
int asint = asfloat * 100;
int asint_fix = 0.5f + asfloat * 100;
cout << "0.03 * 100 = " << asint << endl;
cout << "0.03 * 100 (with the +0.5f fix) = " << asint_fix << endl;
return 0;
}

Returns:

0.03 * 100 = 2
0.03 * 100 (with the +0.5f fix) = 3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's because floating point numbers cannot represent decimal quantities exactly.

The floating-point number format your computer uses is binary. That means it can exactly represent 1/2, 1/4, 1/8, 1/16, ..., and combinations thereof. So, you can say 0.5, or 0.25, or even 0.75 (0.5 + 0.25) and those will be exact in floating point. But, 0.01 cannot be created with combinations of those fractions; therefore, its value is approximate. Similar story with the other numbers you tested.

This is an inherent limitation with using binary floating point. It's not "super odd"; this is Floating Point 101. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...