C/C++ 中的 abs()、labs() 和 llabs() 函数
在 C++ 的 cstdlib 库中,有一些函数可用于获取绝对值,除了 abs 以外。abs 通常用于 C 中的 int 类型输入,以及 C++ 中的 int、long、long long。其他函数用于 long 和 long long 类型数据等。我们来看看这些函数的用法。
abs() 函数
此函数用于 int 类型数据。因此,它返回给定参数的绝对值。如下所示,其语法类似于以下内容。
int abs(int argument)
示例
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
int x = -145;
int y = 145;
cout << "Absolute value of " << x << " is: " << abs(x) << endl;
cout << "Absolute value of " << y << " is: " << abs(y) << endl;
}输出
Absolute value of -145 is: 145 Absolute value of 145 is: 145
labs() 函数
此函数用于 long 类型数据。因此,它返回给定参数的绝对值。如下所示,其语法类似于以下内容。
long labs(long argument)
示例
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
long x = -9256847L;
long y = 9256847L;
cout << "Absolute value of " << x << " is: " << labs(x) << endl;
cout << "Absolute value of " << y << " is: " << labs(y) << endl;
}输出
Absolute value of -9256847 is: 9256847 Absolute value of 9256847 is: 9256847
llabs() 函数
此函数用于 long long 类型数据。因此,它返回给定参数的绝对值。如下所示,其语法类似于以下内容。
long long labs(long long argument)
示例
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
long long x = -99887654321LL;
long long y = 99887654321LL;
cout << "Absolute value of " << x << " is: " << llabs(x) << endl;
cout << "Absolute value of " << y << " is: " << llabs(y) << endl;
}输出
Absolute value of -99887654321 is: 99887654321 Absolute value of 99887654321 is: 99887654321
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP