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

C++ abs() 函数使用方法及示例

C++ Fonction de bibliothèque <cmath>

C ++中的abs()函数返回参数的绝对值。

abs函数与C ++中的fabs()相同。

该函数在<cmath>头文件中定义。

[数学] |x| = abs(x) [C++ 语言]

abs()原型[从C ++ 11标准开始]

double abs(double x);
float abs(float x);
long double abs(long double x);
double abs(T x); // 为整型

在ABS()函数只有一个参数,并返回类型的值double,float或long double类型。

abs()参数

abs()函数采用单个参数x,其返回绝对值。

abs()返回值

abs()函数返回x的绝对值,即| x |。

Exemple1:abs()函数在C ++中如何工作?

#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;
}

Lorsque le programme est exécuté, la sortie est :

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

Exemple2:整数类型的abs()函数

#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;
}

Lorsque le programme est exécuté, la sortie est :

C++ Fonction de bibliothèque <cmath>