在C++中,可以使用标准库中的 abs
函数来求绝对值。该函数接受一个整数或浮点数作为参数,并返回其绝对值。示例如下:
#include <iostream>
#include <cmath>
int main() {
int num1 = -10;
double num2 = -3.14;
int absNum1 = abs(num1);
double absNum2 = abs(num2);
std::cout << "Absolute value of " << num1 << " is " << absNum1 << std::endl;
std::cout << "Absolute value of " << num2 << " is " << absNum2 << std::endl;
return 0;
}
在上面的示例中,我们使用 abs
函数分别求得了 -10
和 -3.14
的绝对值,并输出到控制台。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:如何精确使用C++求绝对值