-2

With the following code:

    int ten{ 1 };
    double zeroPnine{ 0.9 };

    cout << ten - zeroPnine << endl; // 0.1
    cout << (ten - zeroPnine) * 10 << endl; // 1
    cout << static_cast <int>(ten - zeroPnine) << endl; // 0    
    cout << static_cast <int>((ten - zeroPnine) * 10 )<< endl; // 1

I am expecting the last line to output 1, but actual output is in actually 0, how come?

Full output: 0.1
1
0
0

6
  • Because of the imprecisions of the floating point format on computers, which can cause rounding errors. Commented Feb 19, 2015 at 6:56
  • If you print out the last line without the static cast, it shows 1, or at least something close to 1. But if you say "((ten - zeroPnine) * 10) == 1", it says false for the reason Joachim states. The values are imprecise. Floating points should be relied upon for relative values, not discrete points. Commented Feb 19, 2015 at 6:57
  • 0.9 is not an integer by the way. Commented Feb 19, 2015 at 7:00
  • I understand 0.9 isn't integer, but 1 - 0.9 = 0.1, and 0.1 * 10 should give me 1, why is it a problem? Commented Feb 19, 2015 at 7:12
  • Due to how floating point numbers work, 0.9 is actually 0.90000000000000002220446049250313080847263336181640625 Commented Feb 19, 2015 at 7:45

1 Answer 1

1

Best advice would be to avoid using static_cast to convert double.

Try converting double to int before doing the calculation if you want the answer to be integers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.