C++ fabs()

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

Mathematically, fabs(num) = |num|.

Example

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

int main() {

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

fabs() Syntax

The syntax of the fabs() function is:

fabs(double num);

fabs() Parameters

The fabs() 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

fabs() Return Value

The fabs() function returns:

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

fabs() Prototypes

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

double fabs(double num);

float fabs(float num);

long double fabs(long double num);

// for integral type
double fabs(T num);

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


Example 1: C++ fabs()

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

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

Output

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

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

#include <iostream>
#include <cmath>

using namespace std;

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

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

Output

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