函式
<cstdlib>

abs

int abs (int n);
     int abs (     int n);long int abs (long int n);
          int abs (          int n);     long int abs (     long int n);long long int abs (long long int n);
絕對值
返回引數 n 的絕對值 (/n/)。

在 C++ 中,此函式也在標頭檔案 <cmath> 中為浮點型別進行了過載(參見 cmath abs),在標頭檔案 <complex> 中為複數進行了過載(參見 complex abs),並在標頭檔案 <valarray> 中為 valarray 進行了過載(參見 valarray abs)。

引數

n
整數值。

返回值

n 的絕對值。

可移植性

在 C 語言中,只存在 int 版本。
對於 long int 的等效版本,請參見 labs
對於 long long int 的等效版本,請參見 llabs

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
/* abs example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* abs */

int main ()
{
  int n,m;
  n=abs(23);
  m=abs(-11);
  printf ("n=%d\n",n);
  printf ("m=%d\n",m);
  return 0;
}

輸出

n=23
m=11


資料競爭

併發呼叫此函式是安全的,不會導致資料競爭。

異常 (C++)

無丟擲保證:此函式不會丟擲異常。

如果結果無法用返回型別表示(例如,在採用二進位制補碼錶示有符號值的實現中,abs(INT_MIN)),則會導致未定義行為

另見