C语言“全能比较函数”新鲜出炉(第二版),任意数据类型

2014-11-23 23:36:28 · 作者: · 浏览: 8

第一版:
[cpp]
#include

// 下面就是“全能比较函数”,a>b返回整数,a #define COMPARE(TYPE,a,b) ((TYPE)a-(TYPE)b)

int main(int argc, char *argv[])
{
double a=1, b=1.5, c;
int x=10, y=1, z;
char m='m', n='n', k;

c = COMPARE(double, a, b);
printf("%lf \n", c);

z = COMPARE(int, x, y);
printf("%d \n", z);

k = COMPARE(char, m, n);
printf("%d \n", k);

return 0;
}

返回的数据类型不统一,跟输入的数据类型有关;能不能统一返回int类型的结果呢?


第二版:比较结果为int类型

[cpp]
#include

// 下面就是“全能比较函数”,a>b返回整数,a #define COMPARE(TYPE,a,b) (((TYPE)a-(TYPE)b)==0 0:(((TYPE)a-(TYPE)b)>0 1:-1))

int main(int argc, char *argv[])
{
int result;
double a=1, b=1.5;
int x=10, y=1;
char m='m', n='n';
float f1=6.02, f2=6.0200002;

result = COMPARE(double, a, b);
printf("%d \n", result);

result = COMPARE(int, x, y);
printf("%d \n", result);

result = COMPARE(char, m, n);
printf("%d \n", result);

result = COMPARE(float, f1, f2);
printf("%d \n", result);

return 0;
}