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:
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 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;}
Code Explanation
- Line 6–7: We create
intvariablesresult1andresult2. - Line 9–11: We create
doublevariablesxandy. - Line 14–15: Using the
fabs()function, we take the absolute value ofxandyvariables and assign the outputs respectively to variablesresult1andresult2. - Line 17 & 18: we printed the variables
result1andresult2.
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 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;}
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 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;}