在C++中,求絕對值可以使用標(biāo)準(zhǔn)庫函數(shù)abs()來實現(xiàn)。abs()函數(shù)接受一個整數(shù)參數(shù),返回該整數(shù)的絕對值。
例如:
#include <iostream>
#include <cstdlib>
int main() {
int num = -5;
int abs_num = abs(num);
std::cout << "The absolute value of " << num << " is " << abs_num << std::endl;
return 0;
}
運行以上代碼,將輸出:
The absolute value of -5 is 5
如果需要求浮點數(shù)的絕對值,可以使用標(biāo)準(zhǔn)庫函數(shù)fabs()來實現(xiàn)。fabs()函數(shù)接受一個浮點數(shù)參數(shù),返回該浮點數(shù)的絕對值。
例如:
#include <iostream>
#include <cmath>
int main() {
double num = -5.5;
double abs_num = fabs(num);
std::cout << "The absolute value of " << num << " is " << abs_num << std::endl;
return 0;
}
運行以上代碼,將輸出:
The absolute value of -5.5 is 5.5