第一版:
[cpp]
#include <stdio.h>
// 下面就是“全能比較函數”,a>b返回整數,a<b返回負數,a==b返回0
#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 <stdio.h>
// 下面就是“全能比較函數”,a>b返回整數,a<b返回負數,a==b返回0
#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;
}