fabs, fabsf, fabsl, fabsd32, fabsd64, fabsd128

< c‎ | numeric‎ | math
定义于头文件 <math.h>
float       fabsf( float arg );
(1) (C99 起)
double      fabs( double arg );
(2)
long double fabsl( long double arg );
(3) (C99 起)
_Decimal32  fabsd32( _Decimal32 arg );
(4) (C23 起)
_Decimal64  fabsd64( _Decimal64 arg );
(5) (C23 起)
_Decimal128 fabsd128( _Decimal128 arg );
(6) (C23 起)
定义于头文件 <tgmath.h>
#define fabs( arith )
(7) (C99 起)
1-6) 计算浮点值 arg 的绝对值。

拥有十进制浮点参数的函数当且仅当实现预定义 __STDC_IEC_60559_DFP__ (即实现支持十进制浮点数)才被声明。

(C23 起)
7) 泛型宏:若实参拥有 _Decimal128_Decimal64_Decimal32 (C23 起)long doubledoublefloat 类型,则分别调用 fabsd128fabsd64fabsd32 (C23 起)fabslfabsfabsf 。否则若实参拥有整数类型,则调用 fabs 。否则若实参为复数,则宏调用对应的复函数( cabsfcabscabsl )。否则行为未定义。

参数

arg - 浮点值
arith - 浮点或整数值

返回值

若成功,则返回 arg 的绝对值( |arg| )。值是准确的,且不依赖任何舍入模式。

错误处理

此函数不受制于任何指定于 math_errhandling 的错误条件。

若实现支持 IEEE 浮点算术( IEC 60559 ),则

  • 若参数为 ±0 ,则返回 +0
  • 若参数为 ±∞ ,则返回 +∞
  • 若参数为 NaN ,则返回 NaN

示例

#include <stdio.h>
#include <math.h>
 
/* 此数值积分假定所有面积均为正。 */
#define PI 3.14159
double num_int (double a, double b,
                double f(double),
                unsigned n) {
    if (a == b) return 0.0;
    if (n == 0) n=1;   /* 避免除以零 */
    double h = (b-a)/n;
    double sum = 0.0;
    for (unsigned k=0; k < n; ++k)
        sum += h*fabs(f(a+k*h));
    return sum;
}
 
int main(void)
{
    printf("fabs(+3) = %f\n", fabs(+3.0));
    printf("fabs(-3) = %f\n", fabs(-3.0));
    // 特殊值
    printf("fabs(-0) = %f\n", fabs(-0.0));
    printf("fabs(-Inf) = %f\n", fabs(-INFINITY));
 
    printf("%f\n", num_int(0.0,2*PI,sin,100000));
 
}

输出:

fabs(+3) = 3.000000
fabs(-3) = 3.000000
fabs(-0) = 0.000000
fabs(-Inf) = inf
4.000000

引用

  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.7.2 The fabs functions (p: 181)
  • 7.25 Type-generic math <tgmath.h> (p: 272-273)
  • F.10.4.2 The fabs functions (p: 382)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.7.2 The fabs functions (p: 248)
  • 7.25 Type-generic math <tgmath.h> (p: 373-375)
  • F.10.4.2 The fabs functions (p: 524)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.7.2 The fabs functions (p: 228-229)
  • 7.22 Type-generic math <tgmath.h> (p: 335-337)
  • F.9.4.2 The fabs functions (p: 460)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.5.6.2 The fabs function

参阅

(C99)
计算整数值的绝对值( |x|
(函数)
(C99)(C99)(C99)
从一个给定值的绝对值和另一个给定值的符号产生值
(函数)
(C99)
检查给定数是不是负数
(宏函数)
(C99)(C99)(C99)
计算复数的模(绝对值)
(函数)