| 这是我第一次做这么大的C语言东东哦,做了好几天哦,呵呵,C语言里需要掌握的基本的知识以及基础的算法都已经包含在里面了,这个用了指针,其实感觉指针也不是很难掌握的哦,呵呵,以下的程序在DEV-C++下编译通过,若要在VC下编译,请把主函数开关的int main改为main 。 |
| #include<stdlib.h> #include<stdio.h> #include<string.h> struct student { int id; char name[20]; float cj[3]; float avg; }stu[50]; //定义50个元素的结构数组 int count=0; //定义一个全局变量,存储学生人数 void input(struct student *p) //输入函数 { int i; printf("\n学号:"); fflush(stdin); scanf("%d",&p->id); printf("\n姓名:"); fflush(stdin); gets(p->name); printf("\n三门成绩:\n"); for (i=0;i<3;i++) { printf("成绩%d: ",i+1); fflush(stdin); scanf("%f",&p->cj[i]); } p->avg=(p->cj[0]+p->cj[1]+p->cj[2]) / 3; //计算平均成绩 } void display(struct student *p) //输出函数 { int i; printf("学号\t姓名\t平均成绩\n"); for (i=0;i<count;i++,p++) { printf("%d\t",p->id); printf("%s\t",p->name); printf("%.2f\n",p->avg); } } void sort(struct student *p) //排序函数 { int i,j; struct student temp; for (i=0;i<count;i++) { for (j=0;j<count-i-1;j++,p++) { if ((p->avg) < ((p+1)->avg)) { temp=*p; *p=*(p+1); *(p+1)=temp; } } p=stu; //每比较完一回都要指针归位 } } void insert(struct student *p) //插入函数 { int i,j; struct student temp; //定义一个临时的结构存储输入的新学员 input(&temp); //因为不是数组,所以要加个取地址符 for (i=0;i<count;i++,p++) { if (temp.avg > p->avg) break; } for (j=count;j>i;j--) *(p+j)=*(p+j-1); *(p+i)=temp; count++; //学员人数加1 } int main() { struct student *ps; char ch='y'; ps=stu; //定义一指针指向结构数组第一位 printf("请输入学员信息:\n"); do{ ch==' '; input(ps); //调用输入函数输入学生信息 ps++; //指针向结构数组后移一位 count++; //学生人数加1 printf("\n 是否继续?<y or n>"); fflush(stdin); ch=getchar(); }while(ch=='y'); printf("\n排序前的学员信息如下:\n"); ps=stu; //指针归位 display(ps); //调用输出函数输出学生信息 printf("\n排序后的学员信息如下:\n"); ps=stu; //指针归位 sort(ps); //调用排序函数 ps=stu; //指针归位 display(ps); //调用输出函数输出学生信息 ps=stu; //指针归位 printf("\n是否要插入新学员?<y or n>"); fflush(stdin); ch=getchar(); if(ch == 'y') insert(ps); printf("\n插入新学员后的学员信息如下:\n"); ps=stu; //指针归位 display(ps); //调用输出函数输出学生信息 system("pause"); } |