共用方式為


abs、_abs64

計算絕對值。

int abs( 
   int n 
);
long abs( 
   long n 
);   // C++ only
long long abs( 
   long long n 
);   // C++ only
double abs( 
   double n 
);   // C++ only
long double abs(
   long double n
);   // C++ only
float abs(
   float n 
);   // C++ only
__int64 _abs64( 
   __int64 n 
);

參數

  • n
    整數值。

傳回值

abs 函式會傳回其參數的絕對值。 不會回傳錯誤。

備註

因為 C++ 允許多載,您可以呼叫會接受並傳回 long、long long、float、double 和 long double 值的 abs 多載。 在 C 程式中,abs 一律接受並傳回 int 。

Microsoft 專有的

由於可使用任何整數類資料類型表示的負整數範圍大於可使用該類型表示的正整數範圍,因此可以提供引數給無法轉換的 abs。 如果引數的絕對值無法由傳回類型表示,則 abs 函式會傳回未變更的引數值。 具體來說,abs(INT_MIN) 傳回 INT_MIN、labs(LONG_MIN) 傳回 LONG_MIN、llabs(LLONG_MIN) 傳回 LLONG_MIN,以及 _abs64(_I64_MIN) 傳回 _I64_MIN。 這表示,abs 函式不能用來保證正值。

結束 Microsoft 專有

需求

常式

必要的標頭

abs

<math.h>

_abs64

<stdlib.h>

範例

這個程式會計算並顯示數個數字的絕對值。

// crt_abs.c
// Build: cl /W3 /TC crt_abs.c
// This program demonstrates the use of the abs function
// by computing and displaying the absolute values of
// several numbers.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>

int main( void )
{
    int ix = -4;
    long lx = -41567L;
    long long llx = -9876543210LL;
    __int64 wx = -1;

    // absolute 32 bit integer value
    printf_s("The absolute value of %d is %d\n", ix, abs(ix));

    // absolute long integer value
    printf_s("The absolute value of %ld is %ld\n", lx, labs(lx));

    // absolute long long integer value
    printf_s("The absolute value of %lld is %lld\n", llx, llabs(llx));

    // absolute 64 bit integer value
    printf_s("The absolute value of 0x%.16I64x is 0x%.16I64x\n", wx, 
        _abs64(wx));

    // Integer error cases:
    printf_s("Microsoft implementation-specific results:\n");
    printf_s(" abs(INT_MIN) returns %d\n", abs(INT_MIN));
    printf_s(" labs(LONG_MIN) returns %ld\n", labs(LONG_MIN));
    printf_s(" llabs(LLONG_MIN) returns %lld\n", llabs(LLONG_MIN));
    printf_s(" _abs64(_I64_MIN) returns 0x%.16I64x\n", _abs64(_I64_MIN));
}
  

.NET Framework 對等用法

System::Math::Abs

請參閱

參考

資料轉換

浮點支援

_cabs

fabs、fabsf

labs、llabs

imaxabs