第一种
#include <stdio.h>
#include <math.h>
int main() {
int x=2;
printf("%f",pow(x,3));
}
8.000000
--------------------------------
Process exited after 0.04138 seconds with return value 0
请按任意键继续. . .
第二种
#include <stdio.h>
#define cube(x) (1.0*x*x*x)
int main() {
int x=2;
printf("%f",cube(x));
}
#include <stdio.h>
#define cube(x) (1.0*x*x*x)
int main() {
printf("%f",cube(2));
}
8.000000
--------------------------------
Process exited after 0.03931 seconds with return value 0
请按任意键继续. . .
首先通过例子引入,这就是带参数的宏,在定义宏的时候那个变量只是一个形式,并没有真正定义变量,在函数中运行的时候你可以直接在宏定义中写数值,也可以写函数中定义的变量。使用得当可以偷不少懒。
接下来看一下易错点
#include <stdio.h>
#define error1(x) (x*57.29)
#define error2(x) (x)*57.29
int main() {
printf("%f\n",error1(5+2));
printf("%f\n",error2(180/error2(1)));
}
119.580000
590785.938000
--------------------------------
Process exited after 0.03801 seconds with return value 0
请按任意键继续. . .
会发现运行结果和我们预期不一致,原因就是运算时的符号优先级,所以------------
一切都要带括号,参数(x)和整个值。
这时候再去看看上面定义的cube宏,是不是错了?
#include <stdio.h>
#define cube(x) (1.0*x*x*x)
int main() {
printf("%f",cube(2+1));
}
7.000000
--------------------------------
Process exited after 0.04548 seconds with return value 0
请按任意键继续. . .
应该定义成这样--
#include <stdio.h>
#define cube(x) (1.0*(x)*(x)*(x))
int main() {
printf("%f",cube(2+1));
}
27.000000
--------------------------------
Process exited after 0.03869 seconds with return value 0
请按任意键继续. . .
还有一点就是宏定义后面不能加;
这点应该没啥问题。