Namespaces
Variants

std:: abs (float) , std:: fabs, std:: fabsf, std:: fabsl

From cppreference.net
Common mathematical functions
Nearest integer floating point operations
(C++11)
(C++11)
(C++11) (C++11) (C++11)
Floating point manipulation functions
(C++11) (C++11)
(C++11)
(C++11)
Classification and comparison
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Types
(C++11)
(C++11)
(C++11)
Macro constants
定义于头文件 <cmath>
定义于头文件 <cstdlib>
(1)
float abs ( float num ) ;

double abs ( double num ) ;

long double abs ( long double num ) ;
(C++23 前)
constexpr /* floating-point-type */
abs ( /* floating-point-type */ num ) ;
(C++23 起)
定义于头文件 <cmath>
(2)
float fabs ( float num ) ;

double fabs ( double num ) ;

long double fabs ( long double num ) ;
(C++23 前)
constexpr /* floating-point-type */
fabs ( /* floating-point-type */ num ) ;
(C++23 起)
float fabsf ( float num ) ;
(3) (C++11 起)
(C++23 起 constexpr)
long double fabsl ( long double num ) ;
(4) (C++11 起)
(C++23 起 constexpr)
附加重载 (C++11 起)
定义于头文件 <cmath>
template < class Integer >
double fabs ( Integer num ) ;
(A) (C++11 起)
(C++23 起 constexpr)
1-4) 计算浮点值 num 的绝对值。 标准库为所有 cv 未限定浮点类型提供了 std::abs std::fabs 的重载版本,其参数类型与 num 的类型相同。 (C++23 起)
A) 为所有整数类型提供了额外的重载,这些类型被视为 double
(since C++11)

对于整型参数, std::abs 的整型重载版本 可能是更合适的匹配。若使用无法通过 整型提升 转换为 int 的无符号整型参数调用 std::abs ,则程序属于非良构。

目录

参数

num - 浮点数或整数值

返回值

如果成功,返回 arg 的绝对值( |arg| )。返回值是精确的,且不依赖于任何舍入模式。

错误处理

此函数不受 math_errhandling 中指定的任何错误条件约束。

如果实现支持 IEEE 浮点算术 (IEC 60559),

  • 若参数为 ±0,则返回 +0。
  • 若参数为 ±∞,则返回 +∞。
  • 若参数为 NaN,则返回 NaN。

注释

额外的重载不需要完全按照 (A) 提供。只需确保对于整数类型的实参 num std :: fabs ( num ) std :: fabs ( static_cast < double > ( num ) ) 具有相同效果即可。

示例

#include <cmath>
#include <iostream>
int main()
{
    std::cout << "abs(+3.0) = " << std::abs(+3.0) << '\n'
              << "abs(-3.0) = " << std::abs(-3.0) << '\n';
    // 特殊值
    std::cout << "abs(-0.0) = " << std::abs(-0.0) << '\n'
              << "abs(-Inf) = " << std::abs(-INFINITY) << '\n'
              << "abs(-NaN) = " << std::abs(-NAN) << '\n';
}

可能的输出:

abs(+3.0) = 3
abs(-3.0) = 3
abs(-0.0) = 0
abs(-Inf) = inf
abs(-NaN) = nan

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用标准 发布行为 正确行为
LWG 2192 C++98 std::abs 的重载版本
在两个头文件中声明不一致
在两个头文件中
均声明这些重载版本
LWG 2735 C++11 返回 double 的整型 std::abs
重载版本被错误要求
移除了该要求

参见

计算整型数值的绝对值( |x|
(函数)
(C++11) (C++11) (C++11)
复制浮点数值的符号
(函数)
(C++11)
检查给定数值是否为负
(函数)
返回复数的模
(函数模板)
对 valarray 的每个元素应用函数 abs
(函数模板)
C 文档 for fabs