例题9.6-9.7
例题9.6
#include<stdio.h> struct Student { int num; char name[20]; char sex; int age; }stu[3]={{10101,"lilin",'M',18},{10101,"zhang fang",'M',19},{10104,"wang min",'F',20}},*p; int main() { printf("No. Name sex age\n"); for(p=stu;p<stu+3;p++) printf("%5d %-20s %2c %4d\n",p->num,p->name,p->sex,p->age); return 0; }
No. Name sex age 10101 lilin M 18 10101 zhang fang M 19 10104 wang min F 20 -------------------------------- Process exited after 0.3117 seconds with return value 0 请按任意键继续. . .
总结:
指针指向数组,正常输出,未出现错误。
例题9.7
#include<stdio.h> #define N 3 void input(struct Student stu[]); struct Student max(struct Student stu[]); void print(struct Student stu); struct Student { int num; char name[20]; float score[3]; float aver; }; int main() { struct Student stu[N],*p=stu; input(p); print(max(p)); return 0; } void input(struct Student stu[]) { int i=0; printf("请输入各学生的信息:学号、姓名、三门课成绩"); for(;i<N;i++) { scanf("%d %s %f %f %f",&stu[i].num,stu[i].name,&stu[i].score[0],&stu[i].score[1],&stu[i].score[2]); stu[i].aver=(stu[i].score[0]+stu[i].score[1]+stu[i].score[2]); } } struct Student max(struct Student stu[]) { int i,m=0; for(i=0;i<N;i++) { if(stu[i].aver>stu[m].aver) m=i; return stu[m]; } } void print(struct Student stud) { printf("\n输出成绩最高学生信息:"); printf("学号:%d\n姓名:%s\n三门课成绩:%5.1f,%5.1f,%5.1f\n平均成绩:%6.2f\n",stud.num,stud.name,stud.score[0],stud.score[1],stud.score[2],stud.aver); }
请输入各学生的信息:学号、姓名、三门课成绩 10 w 66 999 888 11 j 66 88 75 12 o 99 87 33 输出成绩最高学生信息:学号:10 姓名:w 三门课成绩: 66.0,999.0,888.0 平均成绩:1953.00 -------------------------------- Process exited after 92.89 seconds with return value 0 请按任意键继续. . .
这个程序是照的打的,我自己打的会更加复杂一些,在打完后我跟着这个程序的思路进行了一遍,可以理顺它的思路。