编译预处理和宏2(带参数的宏)

第一种

#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
请按任意键继续. . .

还有一点就是宏定义后面不能加;

这点应该没啥问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值