宏演示
*/
#include <stdio.h>
#define PI 3.14f
#define CIRCLE(r) 2 * PI * r
int main() {
int radius = 0;
const float pi = 3.14f;
printf("请输入一个半径:");
scanf("%d", &radius);
printf("周长是%g\n", 2 * PI * radius);
printf("周长是%g\n", CIRCLE(radius));
printf("周长是%g\n", 2 * pi * radius);
return 0;
}
/*
宏练习
*/
#include <stdio.h>
#define AREA(length, wdith) length * width
int main() {
int length = 0, width = 0;
printf("请输入长和宽:");
scanf("%d%d", &length, &width);
printf("面积是%d\n", AREA(length, width));
return 0;
}
/*
宏练习
*/
#include <stdio.h>
#define ABS(n) n >= 0 ? n : 0 - n
#define MAX(x, y) x >= y ? x : y
int abs(int num) {
if (num >= 0) {
return num;
}
else {
return 0 - num;
}
}
int main() {
int num = 0;
printf("请输入一个数字:");
scanf("%d", &num);
printf("绝对值是%d\n", abs(num));
printf("绝对值是%d\n", ABS(num));
printf("MAX(5, 8)是%d\n", MAX(5, 8));
return 0;
}
/*
宏参数演示
*/
#include <stdio.h>
#define NEG(n) n = 0 - n
void neg(int *p_num) {
*p_num = 0 - *p_num;
}
int main() {
int num = 10;
neg(&num);
printf("num是%d\n", num);
NEG(num);
printf("NEG(num)是%d\n", num);
return 0;
}
/*
宏演示
*/
#include <stdio.h>
#define SUB(x, y) ((x) - (y))
int main() {
printf("SUB(7, 4)是%d\n", SUB(7, 4));
printf("20 - SUB(7, 4)是%d\n", 20 - SUB(7, 4));
printf("SUB(10, 6 - 3)是%d\n", SUB(10, 6 - 3));
return 0;
}
/*
长方形面积宏练习
*/
#include <stdio.h>
#define AREA(length, width) ((length) * (width))
int main() {
printf("63 / AREA(3, 7)是%d\n", 63 / AREA(3, 7));
printf("AREA(3 + 4, 8)是%d\n", AREA(3 + 4, 8));
return 0;
}
/*
宏演示
*/
#include <stdio.h>
#define SQUARE(r) ((r) * (r))
int main() {
int num = 5;
printf("SQUARE(6)是%d\n", SQUARE(6));
printf("SQUARE(++num)是%d\n", SQUARE(++num));
return 0;
}
/*
宏作业
*/
#include <stdio.h>
#define HEX(n) ((n) >= '0' && (n) <= '9' ? (n) - '0' : (n) >= 'a' && (n) <= 'f' ? (n) - 'a' + 10:(n) - 'A' + 10)
int main() {
char ch = 0;
printf("请输入一个十六进制数字字符:");
scanf("%c", &ch);
printf("转换结果是%d\n", HEX(ch));
return 0;
}
/*
宏操作符演示
*/
#include <stdio.h>
#define STR(n) #n
#define LOCAL(n) l_##n
int main() {
int LOCAL(num) = 0;
printf("STR(2 + 3)是%s\n", STR(2 + 3));
LOCAL(num) = 10;
return 0;
}