Unexpected Output when adding two float numbers

前端 未结 3 898
傲寒
傲寒 2020-12-20 22:11

I wrote the following C++ code:

float a, b;
int c;

a = 8.6;
b = 1.4;
c = a + b;

printf(\"%d\\n\", c);

The output is 10.

3条回答
  •  鱼传尺愫
    2020-12-20 22:49

    There's no real difference between the two. They both behave in ways that are unpredictable.

    What you're doing is equivalent to flipping a coin twice and asking what you did differently to get heads one time and tails the other. It's not that you did anything different, it's that this is what happens when you flip coins.

    If you ask a person to add one third and two thirds using 6 digit decimal precision and then round down to an integer, you might get 0 and you might get 1. It will depend on things like whether they represent 2/3 as "0.666666" or "0.6666667" and they're both acceptable. So both 0 and 1 are acceptable answers. If you're not prepared to accept either answer, don't ask that kind of question.

提交回复
热议问题