What is the fabs() function in C++?

Overview

The fabs() function in C++ is used to return the absolute value of an argument passed to the function.

The fabs() function is defined in the cmath header file.

Mathematically, it is represented as: fabs(num)=numfabs(num) = |num|

Syntax

fabs(double num)

Parameter value

The fabs() function takes a single parameter value which is a number of any type: double, float, or long double.

Return value

The fabs() function returns the absolute value of the number passed to it as an argument.

Example 1

Let’s use the fabs() function for double numbers:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
int result1;
int result2;
// for a negative double
double x = -10.25, result;
// for a positve double
double y = 10.25;
result1 = fabs(x);
result2 = fabs(y);
cout << "fabs(" << x << ") = |" << x << "| = " << result1<<endl;
cout << "fabs(" << y << ") = |" << y << "| = " << result2;
return 0;
}

Code Explanation

  • Line 6–7: We create int variables result1 and result2.
  • Line 9–11: We create double variables x and y.
  • Line 14–15: Using the fabs() function, we take the absolute value of x and y variables and assign the outputs respectively to variables result1 and result2.
  • Line 17 & 18: we printed the variables result1 and result2.

Example 2

Let’s use the fabs() function for float numbers:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
int result1;
int result2;
// for a negative float
float x = -3.5f, result;
// for a positve float
float y = 3.5f;
result1 = fabs(x);
result2 = fabs(y);
cout << "fabs(" << x << ") = |" << x << "| = " << result1<<endl;
cout << "fabs(" << y << ") = |" << y << "| = " << result2;
return 0;
}

Example 3

Let’s use the fabs() function for long double numbers:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
int result1;
int result2;
// for a negative long double
long double x = -1.256, result;
// for a positve long double
long double y = 1.256;
result1 = fabs(x);
result2 = fabs(y);
cout << "fabs(" << x << ") = |" << x << "| = " << result1<<endl;
cout << "fabs(" << y << ") = |" << y << "| = " << result2;
return 0;
}

Free Resources