C語(yǔ)言練習(xí)


例10.4?
struct STUDENT
{ int num;
char name[10];
float score;
};
main()
{ struct STUDENT stud[3],*p;
for(p=stud,p<stud+3;p++)
scanf("%d,%s,%f",&p->num, p->name, &p->sex, &p->age, &p->score);
for(p=stud,p<stud+3;p++)
printf("%d,%s,%f\n",p->num, p->name, p->sex, p->age, p->score);
}

[例10.5]普通結(jié)構(gòu)體類型作函數(shù)參數(shù)
struct STUDENT
{ int num;
char name[10];
float score;
};
void PrintStudent(struct STUDENT s) /* 參數(shù)為結(jié)構(gòu)體 */
{ printf("%d,%s,%f\n",s.num,s.name,s.score);
}
main()
{ struct STUDENT a={1002,"ZhaoLi",93.0};
PrintStudent(a);
}

[10.6]結(jié)構(gòu)體數(shù)組作為函數(shù)參數(shù)
struct STUDENT
{ int num;
char name[10];
float score;
};
void ReadStudents(struct STUDENT s[],int n) /* 參數(shù)為結(jié)構(gòu)體數(shù)組 */
{ int i;
for(i=0;i<n;i++)
scanf("%d,%s,%f",&s[i].num, s[i].name, &s[i].score);
}
void PrintStudents(struct STUDENT s[],int n) /* 參數(shù)為結(jié)構(gòu)體數(shù)組 */
{ int i;
for(i=0;i<n;i++)
printf("%d,%s,%f\n",s[i].num, s[i].name, s[i].score);
}
main()
{ struct STUDENT a[3];
ReadStudents(a,3);
PrintStudents(a,3);
}

[10.7]結(jié)構(gòu)體指針作為函數(shù)參數(shù)
struct STUDENT
{ int num;
char name[10];
float score;
};
void ReadStudent(struct STUDENT *p) /* 參數(shù)為結(jié)構(gòu)體指針 */
{ scanf("%d,%s,%f",&p->num, p->name, &p->score);
}
void PrintStudent(struct STUDENT s)
{ printf("%d,%s,%f\n",s.num,s.name,s.score);
}
main()
{ struct STUDENT a;
ReadStudent(&a);
PrintStudent(a);
}

[10.8] 返回值為結(jié)構(gòu)體類型
struct STUDENT
{ int num;
char name[10];
float score;
};
struct STUDENT ReadStudent() /* 返回值類型為結(jié)構(gòu)體 */
{ struct STUDENT s
scanf("%d,%s,%f",&s.num, s.name, &s.score);
return s;
}
void PrintStudent(struct STUDENT s)
{ printf("%d,%s,%f\n",s.num,s.name,s.score);
}
main()
{ struct STUDENT a;
a=ReadStudent();
PrintStudent(a);
}

[10.9] 返回值為結(jié)構(gòu)體指針
struct STUDENT
{ int num;
char name[10];
float score;
};
struct STUDENT *BestStudent(struct STUDENT s[],int n) /* 返回結(jié)構(gòu)體指針 */
{ int i,pos=0;
for(i=1;i<n;i++)
if(s[pos].score<s[i].score)pos=i;
return? &s[pos];
}
void PrintStudent(struct STUDENT s)
{ printf("%d,%s,%f\n",s.num, s.name, s.score);
}
main()
{ struct STUDENT stud[3]={{1001,"LiMing",90.5},
{1002,"ZhaoLi",95.0};
{1003,"WangLin",93.0}};
struct STUDENT *p;
p=BestStudent(stud,3);
PrintStudent(*p);
}

例10.10 計(jì)算下一個(gè)工作日(五天工作制)
enum WEEKDAY{sun,mon,tue,wed,thu,fri,sat};
enum WEEKDAY NextWorkday(enum WEEKDAY w)
{ if(w<fri) w++;
else w=mon;
return w;
}
char *WeekName(enum WEEKDAY w)
{ switch(w)
{ case sun: return("星期日");
case mon: return("星期一");
case tue: return("星期二");
case wed: return("星期三");
case thu: return("星期四");
case fri: return("星期五");
case sat: return("星期六");
}
}
main()
{ enum WEEKDAY? x,y;
int d;
printf("今天是星期幾(星期日=0,星期一=1,……,星期六=6):");
scanf("%d",&d);
x=(enum WEEKDAY)d;
y= NextWorkday(x);
printf("今天是%s,",WeekName(x));
printf("下一個(gè)工作日是%s\n",WeekName(y));
}

