Abs
定义于头文件 <cstdlib>
, <cinttypes>
, <cmath>
。
描述
计算整数的绝对值。如果结果不能由返回类型表示,则行为未定义。
声明
- C++23
- C++11
- C++98
定义于 <cstdlib>
// 1)
int abs (int n);
// 2)
long int abs (long int n);
// 3)
constexpr long long int abs (long long int n);
// 4)
constexpr long labs( long n );
// 5)
constexpr long long llabs( long long n );
// 6)
constexpr /* floating-point-type */
abs( /* floating-point-type */ n );
定义于 <cmath>
// 7)
constexpr /* floating-point-type */
fabs ( /* floating-point-type */ n );
// 8)
constexpr float fabsf( float n );
// 9)
constexpr long double fabsl( long double n );
定义于 <cinttypes>
// 10)
std::intmax_t abs( std::intmax_t n );
// 11)
std::intmax_t imaxabs( std::intmax_t n );
附加重载
// 16)
template< class Integer >
constexpr double fabs ( Integer n );
定义于 <cstdlib>
// 1)
int abs ( int n );
// 2)
long int abs ( long int n );
// 3)
long long int abs ( long long int n );
// 4)
long labs( long n );
// 5)
long long llabs( long long n );
// 6)
float abs( float n );
// 7)
double abs( double n );
// 8)
long double abs( long double n );
定义于 <cmath>
// 9)
float fabs ( float n );
// 10)
double fabs ( double n );
// 11)
long double fabs ( long double n );
// 12)
float fabsf( float n );
// 13)
long double fabsl( long double n );
定义于 <cinttypes>
// 14)
std::intmax_t abs( std::intmax_t n );
// 15)
std::intmax_t imaxabs( std::intmax_t n );
附加重载
// 16)
template< class Integer >
double fabs ( Integer n );
// 1)
int abs (int n);
// 2)
long int abs (long int n);
// 3)
long labs( long n );
参数
n
- 整型值。
返回值
n 的绝对值。
示例
在这里,我们使用 cstdlib 中的 abs 函数找到负数 5 和 2371041 的绝对值。
#include <iostream>
#include <cstdlib>
int main() {
std::cout << "Abs value of -5: "
<< abs(-5);
std::cout << "Abs value of -2371041: "
<< abs(-2371041);
return 0;
}
结果
Abs value of -5: 5
Abs value of -2371041: 2371041
危险
无异常抛出保证:此函数不抛出任何异常。
如果结果不能由返回类型表示(例如在采用二进制补码的有符号值实现中 abs(INT_MIN)
),则会导致未定义行为。