C++ Math abs
The function calculates the absolute value of a specified number.
Suppose a number is 'x' :
abs(x) = |x|;
Difference between abs and fabs
The abs function does not accept arguments of float or double types, whereas the fabs function can handle arguments of float, double, and integer types.
Syntax
int abs( int x);
long int abs(long int x );
long long int abs(long long int x);
Parameter
x : The value for which the absolute value needs to be calculated.
Return value
It returns the absolute value of x.
Example 1
Let's examine a basic scenario where the value of x is below zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x= -9;
std::cout << "Value of x is :" <<x<< std::endl;
cout<<"Absolute value of x is : "<<abs(x);
return 0;
}
Output:
Value of x is :-9
Absolute value of x is : 9
In this instance, the abs function calculates the absolute value of x and provides a result of 9.
Example 2
Let's consider a straightforward scenario where the value of x is greater than zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x= 89;
std::cout << "Value of x is :" <<x<< std::endl;
cout<<"Absolute value of x is : "<<abs(x);
return 0;
}
Output:
Value of x is :89
Absolute value of x is : 89
In this instance, the abs function calculates the absolute value of x.