C++ fabs()

The fabs() function in C++ returns the absolute value of the argument.

It is defined in <cmath> header file.

[Mathematics] |x| = fabs(x) [C++ Programming]

fabs() prototype [As of C++ 11 standard]

double fabs(double x);
float fabs(float x);
long double fabs(long double x);
double fabs(T x); // For integral type

The fabs() function takes a single argument and returns a value of type double, float or long double type.


fabs() Parameters

The fabs() function takes a single argument, x whose absolute value is returned.


fabs() Return value

The fabs() function returns the absolute value of x i.e. |x|.


Example 1: How fabs() function works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double x = -10.25, result;
    
    result = fabs(x);
    cout << "fabs(" << x << ") = |" << x << "| = " << result << endl;

    return 0;
}

When you run the program, the output will be:

fabs(-10.25) = |-10.25| = 10.25

Example 2: fabs() function for integral types

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    long int x = -23;
    double result;

    result = fabs(x);
    cout << "fabs(" << x << ") = |" << x << "| = " << result << endl;

    return 0;
}

When you run the program, the output will be:

fabs(-23) = |-23| = 23