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
廣告