When do I use fabs and when is it sufficient to use std::abs?

后端 未结 4 2013
野趣味
野趣味 2020-12-02 17:41

I assume that abs and fabs are behaving different when using math.h. But when I use just cmath and std::abs,

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 18:44

    It's still okay to use fabs for double and float arguments. I prefer this because it ensures that if I accidentally strip the std:: off the abs, that the behavior remains the same for floating point inputs.

    I just spent 10 minutes debugging this very problem, due to my own mistake of using abs instead of std::abs. I assumed that the using namespace std;would infer std::abs but it did not, and instead was using the C version.

    Anyway, I believe it's good to use fabs instead of abs for floating-point inputs as a way of documenting your intention clearly.

提交回复
热议问题