Share via


abs, labs, llabs, _abs64

計算引數的絕對值。

語法

int abs( int n );
long labs( long n );
long long llabs( long long n );
__int64 _abs64( __int64 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

參數

n
數值。

傳回值

labsllabs 和 函 _abs64 式會 abs 傳回 參數 n 的絕對值。 沒有傳回錯誤。

備註

因為 C++ 允許多載,所以您可以呼叫採用並傳回 longlong longfloatdoublelong double 值的 abs 的多載。 這些多載定義于 標頭中 <cmath> 。 在 C 程式中, abs 一律接受 並傳 int 回 。

Microsoft 特 有:任何整數類型中可表示的負整數範圍大於該類型中可表示的正整數範圍。 因此,可以為無法轉換的這些函式提供引數。 如果引數的絕對值不能以傳回型別表示,則函 abs 式會傳回未變更的引數值。 具體來說,abs(INT_MIN) 會傳回 INT_MINlabs(LONG_MIN) 會傳回 LONG_MINllabs(LLONG_MIN) 會傳回 LLONG_MIN,且 _abs64(_I64_MIN) 會傳回 _I64_MIN。 實際上, abs 函式無法用來保證正值。

需求

常式 必要的 C 標頭 必要的 C++ 標頭
abs, labs, llabs <math.h><stdlib.h> <cmath><cstdlib><stdlib.h><math.h>
_abs64 <stdlib.h> <cstdlib><stdlib.h>

若要在 C++ 中使用 的多載版本 abs ,您必須包含 <cmath> 標頭。

範例

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

// 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));
}
The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -9876543210 is 9876543210
The absolute value of 0xffffffffffffffff is 0x0000000000000001
Microsoft implementation-specific results:
abs(INT_MIN) returns -2147483648
labs(LONG_MIN) returns -2147483648
llabs(LLONG_MIN) returns -9223372036854775808
_abs64(_I64_MIN) returns 0x8000000000000000

另請參閱

資料轉換
數學和浮點支援
_cabs
fabs, fabsf, fabsl
imaxabs