这个宏调用为什么错了??

#include

#define HARMONIC_MEAN(X, Y) ( 1/((1/X+1/Y) / 2) )

int main(void)
{

printf("harmonic mean of and : %g\n", HARMONIC_MEAN(2, 3));
return 0;
}
调用错了吗?为什么?

error C2124: divide or mod by zero
究其原因,是因为宏定义过程中,变量默认为整型处理,才会导致0除。
把程序稍微改一改,变成:

 #define HARMONIC_MEAN(X, Y) ( 1.0/((1.0/X+1.0/Y) / 2.0) )
int main(void)
{
printf("harmonic mean of and : %f\n", double(HARMONIC_MEAN(2, 3)));
return 0;
}

就OK啦~注意数据类型哈!

在C语言里int/int结果是int,所以1/2=0
修改为:

 #define HARMONIC_MEAN(X, Y) ( 1.0/((1.0/(X)+1.0/(Y)) / 2.0) )