Why use abs() or fabs() instead of conditional negation?

前端 未结 9 743
南方客
南方客 2021-01-31 07:38

In C/C++, why should one use abs() or fabs() to find the absolute value of a variable without using the following code?

int absoluteVal         


        
9条回答
  •  臣服心动
    2021-01-31 07:52

    The first thing that comes to mind is readability.

    Compare these two lines of codes:

    int x = something, y = something, z = something;
    // Compare
    int absall = (x > 0 ? x : -x) + (y > 0 ? y : -y) + (z > 0 ? z : -z);
    int absall = abs(x) + abs(y) + abs(z);
    

提交回复
热议问题