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

C++ How to use the abs() function and examples

C++ Library Function <cmath>

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

The abs function in C ++infabs()The same.

This function is<cmath>Defined in the header file.

[Math] |x| = abs(x) [C++ Language]

abs() prototype [from C ++ 11Standard start]

double abs(double  x);
float abs(float  x);
long double abs(long double  x);
double abs(T  x); // For integer type

In the ABS() function, there is only one parameter, and it returns a value of type double, float, or long double.

The abs() parameter

The abs() function takes a single parameter x and returns its absolute value.

The return value of abs()

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

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

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

The output when running the program is:

abs(-87.91)  =  |-87.91|  = | 87.91

Example2: The abs() function of integer type

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

The output when running the program is:

C++ Library Function <cmath>