函数名: abs
功 能: 求整数的绝对值
头文件:stdlib.h
函数原型:int abs(int i);

程序例:


#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int num = -1234;
    float fnum = 0;
    printf("num: %d |num|: %d\n",num,abs(num));
    num = 1234;
    printf("num: %d |num|: %d\n",num,abs(num));
    num = 0;
    printf("num: %d |num|: %d\n",num,abs(num));
    num = -1234.567;
    printf("num: %d |num|: %d\n",num,abs(num));
    fnum = -1234.567;
    printf("fnum: %f |fnum|: %f\n",fnum,abs((int)fnum));
    num = 1234.567;
    printf("num: %d |num|: %d\n",num,abs(num));
    fnum = 1234.567;
    printf("fnum: %f |fnum|: %f\n",fnum,abs((int)fnum));
    return 0;
}

程序运行结果

[root@localhost abs]# make
[root@localhost abs]# ./Tabs 
num: -1234 |num|: 1234
num: 1234 |num|: 1234
num: 0 |num|: 0
num: -1234 |num|: 1234
fnum: -1234.567017 |fnum|: 0.000000
num: 1234 |num|: 1234
fnum: 1234.567017 |fnum|: 0.000000


在C语言中还有fabs,也是求绝对值的,不同的是,fabs函数参数与返回值为实型。
在32位机上若不用系统的函数及条件语句可以使用以下函数实现取绝对值:
int myabs(int n)
{
    return n * ((n>>31<<1) +1);
}


实例(64位机器测试):


#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int n = 0;
    int m = 0;
    n = -5;
    m = n*((n>>63<<1)+1);
    printf("n:%d |n|:%d\n",n,m);
    n = 6;
    m = n*((n>>63<<1)+1);
    printf("n:%d |n|:%d\n",n,m);
    return 0;
}

程序运行结果:

[root@localhost abs]# make
[root@localhost abs]# ./Tabs 
n:-5 |n|:5
n:6 |n|:6