C++ 标准库 - <cstdlib>

C++ std::abs 对 int / long 等整数求绝对值,声明于 <cstdlib>。浮点用 std::fabs 或 <cmath> 中的重载 std::abs。

原型

int abs(int n);
long labs(long n);

参数

  • n:整数。

返回值

非负的绝对值。

示例

#include <cstdlib>
#include <iostream>

int main() {
    std::cout << std::abs(-5) << " " << std::abs(5) << "\n";
    return 0;
}

输出:

5 5

注意事项

INT_MIN 取绝对值在二进制补码上可能溢出,属于极端情况。

下一页介绍atoi。