C++ cmath abs()

The abs() function in C++ returns the absolute value of the argument. It is defined in the cmath header file.

Mathematically, abs(num) = |num|.

Example

#include <iostream>
#include <cmath>
using namespace std;

int main() {

// get absolute value of -5.5 cout << abs(-5.5);
return 0; } // Output: 5.5

Syntax of abs()

The syntax of the abs() function is:

abs(double num);

abs() Parameters

The abs() function takes the following parameter:

  • num - a floating point number whose absolute value is returned. It can be of the following types:
    • double
    • float
    • long double

abs() Return Value

The abs() function returns:

  • the absolute value of num i.e. |num|

abs() Prototypes

The prototypes of abs() as defined in the cmath header file are:

double abs(double num);

float abs(float num);

long double abs(long double num);

// for integral types
double abs(T num);

Note: The cmath abs() function is identical to the fabs() function.


Example 1: C++ abs()

#include <iostream>
#include <cmath>
using namespace std;

int main() {
  double num = -87.91, result;
    
result = abs(num);
cout << "abs(" << num << ") = |" << num << "| = " << result; return 0; }

Output

abs(-87.91) = |-87.91| = 87.91

Example 2: C++ abs() for Integral Types

#include <iostream>
#include <cmath>

using namespace std;

int main() {
  int num = -101;
  double result;

result = abs(num);
cout << "abs(" << num << ") = |" << num << "| = " << result; return 0; }

Output

abs(-101) = |-101| = 101
Did you find this article helpful?