(C++) std::abs

January 11, 2018 · View on GitHub

 

 

 

 

 

(C++) std::abs

 

std::abs is an STL function to take the absolute value of a number (both int and double).

 

std::abs is defined in the header files cmath.h (for doubles) and cstdlib.h (for integers).

 

 

 

 

 

std::abs on double

 


#include <cassert> #include <cmath> int main() {   const double x = 3.14;   const double y = -x;   assert(x == std::abs(y)); }

 

 

 

 

 

std::abs on int

 


#include <cassert> #include <cstdlib> int main() {   const int x = 3;   const int y = -x;   assert(x == std::abs(y)); }

 

 

 

 

 

Difference between std::abs and std::fabs

 

std::abs can be used to calculate the absolute value of both an integer and a double, where std::fabs can only be used to obtain the absolute value of a double.