main()
{
struct stu
{
int num;
char *name;
char sex;
float score;
} boy1,boy2;
boy1.num=102;
boy1.name="microjava";
printf("input sex and score:");
scanf("%c %f",&boy1.sex,&boy1.score);
boy2=boy1;
printf("Number:%d\nName:%s\n",boy2.num,boy2.name);
printf("Sex:%c\nScore:%5.2f\n",boy2.sex,boy2.score);
}
main()
{
struct stu
{
int num;
char *name;
char sex;
float score;
} boy2,boy1={102,"mcfeng",'M',98.5};
boy2=boy1;
printf("Number:%d\nName:%s\n",boy2.num,boy2.name);
printf("Sex:%c\nScore:%5.2f\n",boy2.sex,boy2.score);
}
计算学生的平均成绩和不及格人数
struct stu
{
int num;
char *name;
char sex;
float score;
}boy[5]={
{101,"Li ping",'M',45},
{102,"Zhang ping",'M',62.5},
{103,"He fang",'F',92.5},
{104,"Cheng ling",'F',87},
{105,"Wang ming",'M',58},
};
main()
{
int i,c=0;
float ave,s=0;
for(i=0;i<5;i++)
{
s+=boy[i].score;
if(boy[i].score<60) c++;
}
printf("s=%5.2f\n",s);
ave=s/5;
printf("average=%5.2f\ncount=%d\n",ave,c);
}
计算一组学生的平均成绩和不及格人数。用结构指针变量作函数参数编程。
struct stu
{
int num;
char *name;
char sex;
float score;
}boy[5]={
{101,"Li ping",'M',45},
{102,"Zhang ping",'M',62.5},
{103,"He fang",'F',92.5},
{104,"Cheng ling",'F',87},
{105,"Wang ming",'M',58},
};
main()
{
struct stu *ps;
void ave(struct stu *ps);
ps=boy;
ave(ps);
}
void ave(struct stu *ps)
{
int c=0,i;
float ave,s=0;
for(i=0;i<5;i++,ps++)
{
s+=ps->score;
if(ps->score<60) c+=1;
}
printf("s=%f\n",s);
ave=s/5;
printf("average=%f\ncount=%d\n",ave,c);
}
通讯录
#define NUM 3
struct mem
{
char name[20];
char phone[18];
};
main()
{
struct mem man[NUM];
int i;
for(i=0;i<NUM;i++)
{
printf("input name:");
gets(man[i].name);
printf("input phone:");
gets(man[i].phone);
}
printf("name\t\t\tphone\n\n");
for(i=0;i<NUM;i++)
{
printf("%s\t\t\t%s\n",man[i].name,man[i].phone);
}
}
1.第一种形式:
#ifdef 标识符
程序段1
#else
程序段2
#endif
它的功能是,如果标识符已被 #define命令定义过则对程序段1进行编译;否则对程序段2进行编译。如果没有程序段2(它为空),本格式中的#else可以没有,即可以写为:
#ifdef 标识符
程序段
#endif
2.第二种形式:
#ifndef 标识符
程序段1
#else
程序段2
#endif
与第一种形式的区别是将“ifdef”改为“ifndef”。它的功能是,如果标识符未被#define命令定义过则对程序段1进行编译,否则对程序段2进行编译。这与第一种形式的功能正相反。
3.第三种形式:
#if 常量表达式
程序段1
#else
程序段2
#endif
它的功能是,如常量表达式的值为真(非0),则对程序段1 进行编译,否则对程序段2进行编译。因此可以使程序在不同条件下,完成不同的功能。
//#define FLAG ok
main()
{
struct stu
{
int num;
char *name;
char sex;
float score;
} *ps;
ps=(struct stu*)malloc(sizeof(struct stu));
ps->num=102;
ps->name="microjava";
ps->sex='M';
ps->score=99.5;
#ifdef FLAG
printf("Number=%d \nScore=%5.2f \n",ps->num,ps->score);
#else
printf("Name=%s \nSex=%c \n",ps->name,ps->sex);
#endif
free(ps);
}
#define R 1
main()
{
float c,r,s;
printf("input a number: ");
scanf("%f",&c);
#if R
r=3.14*c*c;
printf("area of round is:%f\n",r);
#else
s=c*c;
printf("area of square is:%f\n",s);
#endif
}