
C ++中的fabs()函数返回参数的绝对值。
它在<cmath>头文件中定义。
|x| = fabs(x)
fabs()原型[从C ++ 11标准开始]
double fabs(double x); float fabs(float x); long double fabs(long double x); double fabs(T x); // For integral type
fabs()函数只有一个参数,并返回类型的值double,float或long double类型。
fabs()参数
fabs()函数采用单个参数x,其返回绝对值。
fabs()返回值
fabs()函数返回x的绝对值,即| x |。
示例1:fabs()函数在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;
}运行该程序时,输出为:
fabs(-10.25) = |-10.25| = 10.25
示例2:整数类型的fabs()函数
#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;
}运行该程序时,输出为:
fabs(-23) = |-23| = 23