C++ fabs()

C++ fabs() returns absolute value of given argument.

Syntax

The syntax of C++ fabs() is

fabs(x)

where

ParameterDescription
xA double, float, long double, or integral type value.

Returns

The return value depends on the type of value passed for parameter x.

The return value of fabs(x) is

  • double if x is double or integral type value.
  • float if x is float.
  • long double if x is long double.

The synopsis of fabs() function is

double fabs(double x);
float fabs(float x);
long double fabs(long double x);
double fabs(T x); // for integral type argument value

fabs() is a function of cmath library. Include cmath library at the start of program, if using fabs() function.

Example

In this example, we read a value from user into variable x, and find the absolute value of x using fabs() function.

C++ Program

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

int main() {
    double x;
    cout << "Enter a value : ";
    cin >> x;
    
    double result = fabs(x);
    cout << "fabs(" << x << ") : " << result << endl;
}

Output

Enter a value : -52
fabs(-52) : 52
Program ended with exit code: 0

Run#2

Absolute value of a positive number is itself.

Enter a value : 25
fabs(25) : 25
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ fabs(), and how to use this function to find the absolute of a value, with the help of examples.