What's the difference between abs and fabs?

后端 未结 3 1265
一向
一向 2020-12-15 04:41

I checked the difference between abs and fabs on python here

As I understand there are some difference regarding the speed and the passed t

3条回答
  •  自闭症患者
    2020-12-15 05:27

    With C++ 11, using abs() alone is very dangerous:

    #include 
    #include 
    
    int main() {
        std::cout << abs(-2.5) << std::endl;
        return 0;
    }
    

    This program outputs 2 as a result. (See it live)

    Always use std::abs():

    #include 
    #include 
    
    int main() {
        std::cout << std::abs(-2.5) << std::endl;
        return 0;
    }
    

    This program outputs 2.5.

    You can avoid the unexpected result with using namespace std; but I would adwise against it, because it is considered bad practice in general, and because you have to search for the using directive to know if abs() means the int overload or the double overload.

提交回复
热议问题