- C標準庫
- C庫 - 首頁
- C庫 - <assert.h>
- C庫 - <complex.h>
- C庫 - <ctype.h>
- C庫 - <errno.h>
- C庫 - <fenv.h>
- C庫 - <float.h>
- C庫 - <inttypes.h>
- C庫 - <iso646.h>
- C庫 - <limits.h>
- C庫 - <locale.h>
- C庫 - <math.h>
- C庫 - <setjmp.h>
- C庫 - <signal.h>
- C庫 - <stdalign.h>
- C庫 - <stdarg.h>
- C庫 - <stdbool.h>
- C庫 - <stddef.h>
- C庫 - <stdio.h>
- C庫 - <stdlib.h>
- C庫 - <string.h>
- C庫 - <tgmath.h>
- C庫 - <time.h>
- C庫 - <wctype.h>
- C程式設計資源
- C程式設計 - 教程
- C - 有用資源
C庫 - fabs() 函式
C語言math庫的fabs()函式接受型別為double的引數(x),返回x的絕對值。此函式在<math.h>標頭檔案中定義,用於計算浮點數的絕對值。
語法
以下是C庫fabs()函式的語法:
double fabs(double x)
引數
此函式只接受一個引數:
x − 這是浮點值。
返回值
此函式返回x的絕對值。
示例
以下是C庫程式,用於演示fabs()函式。
#include <stdio.h>
#include <math.h>
int main () {
int a, b;
a = 1234;
b = -344;
printf("The absolute value of %d is %lf\n", a, fabs(a));
printf("The absolute value of %d is %lf\n", b, fabs(b));
return(0);
}
輸出
以上程式碼產生以下結果:
The absolute value of 1234 is 1234.000000 The absolute value of -344 is 344.000000
示例
下面的程式計算浮點數的絕對值。這裡,我們有兩種型別的絕對值:正數和負數,當這些值傳遞給fabs()函式時,它將顯示結果。
#include <stdio.h>
#include <math.h>
int main() {
double a = 9801.0;
double b = -1831.0;
double res;
res = fabs(a);
printf("The absolute value of %.3lf is %.3lf\n", a, res);
res = fabs(b);
printf("The absolute value of %.3lf is %.3lf\n", b, res);
return 0;
}
輸出
執行以上程式碼後,我們得到以下結果:
The absolute value of 980.000 is 980.000 The absolute value of -1231.000 is 1231.000
示例
這裡,我們計算長雙精度數的近似絕對值。近似數的結果可以使用公式tanh = (1.0 + tanh(x / 2.0)) * (1.0 - tanh(x / 2.0)來識別。
#include <stdio.h>
#include <math.h>
long double my_exp(long double x) {
return (1.0 + tanh(x / 2.0)) * (1.0 - tanh(x / 2.0));
}
int main() {
long double a = -6.546;
long double b = 5.980;
double res;
res = fabs(a);
printf("The absolute value of %.3Lf is %.3lf\n", a, res);
res = fabs(b);
printf("The absolute value of %.3Lf is %.3lf\n", b, res);
return 0;
}
輸出
執行以上程式碼後,我們得到以下結果:
The absolute value of -6.546 is 6.546 The absolute value of 5.980 is 5.980
廣告