abs函数是什么意思?

Python013

abs函数是什么意思?,第1张

abs 函数意思为多种编程语言中的一种用于求数据绝对值的函数。

C++也有abs函数。但是,在C++中使用abs函数要注意存在两种版本,一种是在stdlib.h中定义的版本,另一个是在iostream或cmath头文件中定义的。事实上,在stdlib.h文件中定义的是C的函数,而cmath中的是C++版本。这两种版本有明显的差别。

 C/C++ :

根据ISO C/C++的标准规定,C语言的abs函数仅仅支持整数的绝对值计算(返回值为整型),必须使用fabs才能获得浮点数的绝对值。

C++的abs则可以自然支持对整数和浮点数两个版本(实际上还能够支持复数),如果参数是整数类型,则返回值为相应的整数类型,如果参数为浮点数,则返回值为相应的浮点数类型。

如果在C++程序中,由于头文件关系,不慎使用了C版本的abs函数,并且输入的是一个有小数的浮点数,那么其行为就可能不符合程序员的预期了,因为在传入函数参数时,浮点数会用截断的方式转换为整数。

而使用C++版本的abs函数时,则需要注意返回值类型(如果用printf进行输出,需要使用正确的格式化输出参数)。

因此,通常建议在C++中使用fabs函数(必要时进行强制类型转换),而不要使用abs函数为好。

以上内容参考 百度百科—Abs函数

abs 函数是求绝对值函数,返回整形int

函数描述:INT abs( int n )

需要头文件:<stdlib.h>or <math.h>

例子:

#include <stdio.h>

#include <math.h>

#include <stdlib.h>

void main( void )

{

intix = -4, iy

long lx = -41567L, ly

double dx = -3.141593, dy

iy = abs( ix )

printf( "The absolute value of %d is %d\n", ix, iy)

ly = labs( lx )

printf( "The absolute value of %ld is %ld\n", lx, ly)

dy = fabs( dx )

printf( "The absolute value of %f is %f\n", dx, dy )

}

Output

The absolute value of -4 is 4

The absolute value of -41567 is 41567

The absolute value of -3.141593 is 3.141593