在C++中,使用abs()函數(shù)可以求一個數(shù)的絕對值。abs()函數(shù)定義在cmath頭文件中,可以接受整數(shù)、浮點數(shù)、長整數(shù)、雙精度浮點數(shù)等參數(shù),返回的結(jié)果是參數(shù)的絕對值。
#include <iostream>
#include <cmath>
int main() {
int num = -5;
double num2 = -3.5;
std::cout << "Absolute value of " << num << " is " << abs(num) << std::endl;
std::cout << "Absolute value of " << num2 << " is " << abs(num2) << std::endl;
return 0;
}
上面的代碼演示了如何使用abs()函數(shù)求一個整數(shù)和一個浮點數(shù)的絕對值。輸出結(jié)果為:
Absolute value of -5 is 5
Absolute value of -3.5 is 3.5