std::abs 是 C++ 标准库中的一个函数,用于计算整数的绝对值。它定义在 <cstdlib> 或 <cmath>(对于浮点数)头文件中。
以下是使用 std::abs 的一些示例:
-
对于整数:
#include <cstdlib> | |
#include <iostream> | |
int main() { | |
int num = -10; | |
std::cout << "The absolute value of " << num << " is " << std::abs(num) << std::endl; | |
return 0; | |
} |
-
对于浮点数,你需要使用
<cmath>并可能需要使用std::fabs(对于float和double)或std::absl(对于long double):
#include <cmath> | |
#include <iostream> | |
int main() { | |
double num = -10.5; | |
std::cout << "The absolute value of " << num << " is " << std::fabs(num) << std::endl; | |
return 0; | |
} |
注意:虽然 std::abs 在某些编译器和平台上可能也接受浮点数作为参数,但这不是标准行为。为了可移植性和明确性,最好使用 std::fabs 或 std::absl 对于浮点数。
另外,C++11 引入了模板化的 std::abs 版本,允许你为不同的整数类型(如 int, long, long long 等)使用相同的函数名。这些模板版本定义在 <cstdlib> 中。对于浮点数,仍然应该使用 std::fabs 或 std::absl。
