跳到主要内容

C++ labs() 函数

labs() 函数可以被视为 abs() 函数的 long int 版本。

它定义在 <cstdlib> 头文件中。

[数学] |x| = labs(x) [C++ 编程]

labs() 函数原型 [C++ 11 标准起]

long labs(long x);
long int labs(long int x);

labs() 函数接受一个 longlong int 类型的单个参数,并返回相同类型的值。

labs() 参数

x:一个 longlong int 类型的数据,函数返回其绝对值。

labs() 返回值

labs() 函数返回 x 的绝对值,即 |x|。

示例:C++ 中 labs() 函数如何工作?

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
long int x,y;
x = -9999999L;
y = 10000000L;

cout << "labs(" << x << ") = |" << x << "| = " << labs(x) << endl;
cout << "labs(" << y << ") = |" << y << "| = " << labs(y) << endl;

return 0;
}

当你运行程序时,输出将是:

labs(-9999999) = |-9999999| = 9999999
labs(10000000) = |10000000| = 10000000