Cast to int vs floor

前端 未结 7 1638
夕颜
夕颜 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条回答
  •  旧时难觅i
    2020-11-27 14:28

    EDIT: Because the question may have been modified due to confusion between fabs() and floor().

    Given the original question example lines:

    1.  float foo = (int)(bar / 3.0);
    
    2.  float foo = fabs(bar / 3.0);
    

    The difference is that if bar is negative the result will be negative with the first but positive with the second. The first will be truncated to an integer and the second will return the full decimal value including fractional part.

提交回复
热议问题