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++ 允许重载,您可以调用 abs 的重载,该重载采用和返回 long、long long、float、double 和 long double 值。 在 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));
}