Cast to int vs floor

前端 未结 7 1626
夕颜
夕颜 2020-11-27 14:25

Is there any difference between these:

float foo1 = (int)(bar / 3.0);
float foo2 = floor(bar / 3.0);

As I understand both cases have the sa

7条回答
  •  死守一世寂寞
    2020-11-27 14:42

    There are two main differences:

    1. As others have pointed out, casting to an integer will truncate towards zero, whereas floor() will always truncate towards negative infinity; this is different behaviour for a negative operand.

    2. No one (yet) seems to have pointed out another difference - if your argument is greater than or equal to MAX_INT+1 (or less than -MAX_INT-1) then casting to an int will result in the top-most bits being dropped (C, probably) or undefined behaviour (C++ and possibly C). EG if your int is 32 bits, you will only have a sign bit plus 31 bits of data. So using this with a double that is large in size is going to produce unintended results.

提交回复
热议问题