The abs function is identical to fabs() in C++.
The function is defined in <cmath> header file.
[Mathematics] |x| = abs(x) [C++ Programming]
abs() prototype [As of C++ 11 standard]
double abs(double x); float abs(float x); long double abs(long double x); double abs(T x); // For integral type
The abs() function takes a single argument and returns a value of type double
, float
or long double
type.
abs() Parameters
The abs() function takes a single argument, x whose absolute value is returned.
abs() Return value
The abs() function returns the absolute value of x i.e. |x|.
Example 1: How abs() function works in C++?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = -87.91, result;
result = abs(x);
cout << "abs(" << x << ") = |" << x << "| = " << result << endl;
return 0;
}
When you run the program, the output will be:
abs(-87.91) = |-87.91| = 87.91
Example 2: abs() function for integral types
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long int x = -101;
double result;
result = abs(x);
cout << "abs(" << x << ") = |" << x << "| = " << result << endl;
return 0;
}
When you run the program, the output will be:
abs(-101) = |-101| = 101