English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ How to use fabs() function and example

C++ Library Function <cmath>

C ++The fabs() function returns the absolute value of the parameter.

It is<cmath>Defined in the header file.

|x| = fabs(x)

fabs() prototype [from C ++ 11Standard begins]

double fabs(double x);
float fabs(float x);
long double fabs(long double x);
double fabs(T x); // For integral type

The fabs() function has only one parameter and returns a value of type double, float, or long double.

fabs() parameters

The fabs() function uses a single parameter x and returns its absolute value.

fabs() return value

The fabs() function returns the absolute value of x, that is, |x|.

Example1:The fabs() function in C ++How does it work in C?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double x = -10.25, result;
    
    result = fabs(x);
    cout << "fabs(" << x << ") = |" << x << "| = " << result << endl;
    return 0;
}

When running the program, the output is:

fabs(-10.25) = |-10.25| = 10.25

Example2:The fabs() function of integer type

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    long int x = -23;
    double result;
    result = fabs(x);
    cout << "fabs(" << x << ") = |" << x << "| = " << result << endl;
    return 0;
}

When running the program, the output is:

fabs(-23) = |-23| = 23

C++ Library Function <cmath>