C / C ++中的abs(),labs(),llabs()函数
什么是C库中的整数函数?
整数函数是那些返回整数的精确值的函数。C仅支持整数值。在此函数中,小于或等于参数的最接近整数返回此函数。
整数函数的类型-
int = abs (int n); long = labs (long n); long long = llabs (long long n);
其中n=整数值
什么是abs()
,labs()
,llabs()
的功能呢?
它们定义为<cstdlib>(C标准通用实用程序库)头文件。它们给出输入给它们的整数的精确值作为参数。
abs()函数-在C中,输入的类型为'int',而在C++中,输入的类型为'int,longint或longlongint'。在C中,输出为'int'类型,在C++中,输出具有与输入相同的数据类型。
基本上,abs函数会评估给定值的绝对值,即从数字中删除所有负号和正号后的值。这意味着它将始终返回正数。
例如,
abs(-43)将给出43的输出,因为它是创建来消除负号的。
abs(12)将给出12作为输出,因为没有需要删除的符号。
示例
#include <cstdlib> #include <iostream> using namespace std; int main() { int a = abs(123); int b = abs(-986); cout << "abs(123) = " << a << "\n"; cout << "abs(-986) = " << b << "\n"; return 0; }
输出结果
abs(123) = 123 abs(-986) = 986
labs()函数-在此函数中,输入和输出的类型均为longint,这是该abs()
函数的longint版本。
功能与abs()
删除数字的负数相同,但不同之处在于此方法可以处理长值。
例如,
实验室(245349384932L)=245349384932
实验室(-34235668687987)=34235668687987
示例
#include <cstdlib> #include <iostream> using namespace std; int main() { long int a = labs(437567342L); long int b = labs(-8764523L); cout << "labs(437567342L) = " << a << "\n"; cout << "labs(-8764523L) = " << b << "\n"; return 0; }
输出结果
labs(437567342L) = 437567342 labs(-8764523L) = 8764523
llabs()函数-在此函数中,输入和输出的类型均为longlongint,这是该abs()
函数的longlongint版本。
示例
#include <cstdlib> #include <iostream> using namespace std; int main() { long long int a = llabs(9796546325253547656LL); long long int b = llabs(-1423446557676111567LL); cout << "llabs(9796546325253547656LL) = " << a << "\n"; cout << "llabs(-1423446557676111567LL) = " << b << "\n"; return 0; }
输出结果
llabs(9796546325253547656LL) = 9796546325253547656 llabs(-1423446557676111567LL) = 1423446557676111567