C++的絕對(duì)值函數(shù)是用來(lái)計(jì)算一個(gè)數(shù)的絕對(duì)值的函數(shù)。絕對(duì)值是一個(gè)數(shù)的非負(fù)值,如果這個(gè)數(shù)是正數(shù)或零,則它的絕對(duì)值就是它自身;如果這個(gè)數(shù)是負(fù)數(shù),則它的絕對(duì)值是它的相反數(shù)。
C++中有兩個(gè)常用的絕對(duì)值函數(shù):abs()和fabs()。
int abs(int n);
使用示例:
#include <iostream>
#include <cstdlib>
int main() {
int num = -10;
int result = abs(num);
std::cout << "The absolute value of " << num << " is " << result << std::endl;
return 0;
}
輸出結(jié)果:
The absolute value of -10 is 10
double fabs(double n);
使用示例:
#include <iostream>
#include <cmath>
int main() {
double num = -10.5;
double result = fabs(num);
std::cout << "The absolute value of " << num << " is " << result << std::endl;
return 0;
}
輸出結(jié)果:
The absolute value of -10.5 is 10.5
需要注意的是,abs()函數(shù)和fabs()函數(shù)需要包含相應(yīng)的頭文件。對(duì)于整數(shù),可以包含