程序例:
#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
int myabs(int n)
{
return n * ((n>>31<<1) +1);
}
#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