跳到主要内容

Abs

定义于头文件 <cstdlib>, <cinttypes>, <cmath>

描述

计算整数的绝对值。如果结果不能由返回类型表示,则行为未定义。

声明

定义于 <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 );

参数

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)),则会导致未定义行为。

Abs

定义于头文件 <cstdlib>, <cinttypes>, <cmath>

描述

计算整数的绝对值。如果结果不能由返回类型表示,则行为未定义。

声明

定义于 <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 );

参数

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)),则会导致未定义行为。