学习笔记1:无参宏定义
编程1:define
#include <stdio.h>
#define PI 3.1415926 //制定标识符PI来代替以下编程中的所有3.1415926
void main()
{
double s;
int r;
printf("Please enter the tadius : ");
scanf("%d", &r);
s = PI * r*r;
printf("%g\n\n", s); //%g是根据结果自动选择科学记数法还是一般的小数记数法
}
运行结果:
编程2:typedef与define的区别
#include <stdio.h>
#define PIN1 char*
typedef char* PIN2;
void main()
{
PIN1 x, y; //此处PIN1被替换成char*,于是这一句变成 char* x,y; 也就是char *x和y。define单纯的把PIN1替换成char*
PIN2 a, b; //此处PIN2被替换成char*,于是这一句变成 char* a,b; 也就是char *a和*b。因为typedef定义了a和b的类型,而不是单纯把PIN2替换成char*
printf("By #define : %d %d\n\n", sizeof(x), sizeof(y));
printf("By typedef : %d %d\n\n", sizeof(a), sizeof(b));
}
运行结果:
题目:打印0——999
答案:
#include <stdio.h>
#define A(x) x;x;x;x;x;x;x;x;x;x;
int main(void)
{
int n = 0;
A(A(A(printf("%d ", n++))));
return 0;
}
运行结果:(特别优秀...)
学习笔记2:带参宏定义
编程1:
#include <stdio.h>
#define MAX(a,b) (a>b)?a:b //注意MAX(a,b),宏名和形参之间不能出现空格,形参不需要定义类型
{
int x, y, max;
printf("input two numbers: ");
scanf("%d %d", &x, &y);
max = MAX(x, y);
printf("The max is %d\n\n", max);
}
运行结果:
编程2:strcat函数 粘贴字符串
#include <stdio.h>
#define STR(s1,s2,s3,sum) strcat(strcat(strcat(sum,s1),s2),s3); //把s1粘贴到sum后面,再把s2粘贴到后面,再把s3粘贴到后面
void main()
{
char str1[] = "I ", str2[] = "am ", str3[] = "King!", str[40] = "";
STR(str1, str2, str3, str);
printf("\n\tstr1=%s\n\tstr2=%s\n\tstr3=%s\n\tstr=%s\n\n\n", str1, str2, str3, str);
}
运行结果: