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(double num)
The fabs()
function takes a single parameter value which is a number of any type: double, float, or long double.
The fabs()
function returns the absolute value of the number passed to it as an argument.
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 doubledouble x = -10.25, result;// for a positve doubledouble y = 10.25;result1 = fabs(x);result2 = fabs(y);cout << "fabs(" << x << ") = |" << x << "| = " << result1<<endl;cout << "fabs(" << y << ") = |" << y << "| = " << result2;return 0;}
int
variables result1
and result2
.double
variables x
and y
.fabs()
function, we take the absolute value of x
and y
variables and assign the outputs respectively to variables result1
and result2
.result1
and result2
.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 floatfloat x = -3.5f, result;// for a positve floatfloat y = 3.5f;result1 = fabs(x);result2 = fabs(y);cout << "fabs(" << x << ") = |" << x << "| = " << result1<<endl;cout << "fabs(" << y << ") = |" << y << "| = " << result2;return 0;}
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 doublelong double x = -1.256, result;// for a positve long doublelong double y = 1.256;result1 = fabs(x);result2 = fabs(y);cout << "fabs(" << x << ") = |" << x << "| = " << result1<<endl;cout << "fabs(" << y << ") = |" << y << "| = " << result2;return 0;}