C++ Math fabs
It computes the absolute value of a given number.
Suppose a number is 'x' :
fabs(x) = |x|;
Syntax
float fabs(float x);
double fabs(double x);
int fabs(int x);
Parameter
x : The value for which we need to find the absolute value.
Return value
It returns the absolute value of x.
Example 1
Let's examine a straightforward scenario where the value of x is greater than zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x=11.2;
std::cout << "Value of x is :" <<x<< std::endl;
cout<<"Absolute value of x is : "<<fabs(x);
return 0;
}
Output:
Value of x is :11.2
Absolute value of x is : 11.2
In this instance, the fabs method calculates the absolute magnitude of x=11.2.
Example 2
Let's consider a basic scenario where the value of x is below zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x=-9.4;
std::cout << "Value of x is :" <<x<< std::endl;
cout<<"Absolute value of x is : "<<fabs(x);
return 0;
}
Output:
Value of x is :-9.4
Absolute value of x is : 9.4
In this instance, the fabs function calculates the absolute value of x when x is -9.4.