C语言程序设计 练习题参考答案 第六章 (1) 结构体 综合练习

 /*  6.9 10个学生,每个学生3门课程成绩,求平均分及前五名 */

#include "stdio.h"
#include "conio.h"
#define N 6

struct student  /* 定义结构体数据类型 */
{
  int num;
  char name[10];
  int score[3];   /* 不能使用float */
  float average;
};

void sort(struct student stu[ ] ); /* 函数原型声明, 排序 */
void print( struct student stu[ ] ); /* 函数原型声明, 输出 */
void printtopfive( struct student stu[ ] ); /* 函数原型声明,输出前5名 */

void main()
{
   struct student s[N]; /* s为结构体数组 */
   int i;
   for(i=0;i<N;i++)
   {
      printf("请输入第%d个学生的学号 姓名 成绩1 成绩2 成绩3\n",i+1);
      scanf("%d%s%d%d%d",&s[i].num,s[i].name,&s[i].score[0],
                        &s[i].score[1],&s[i].score[2]);
      s[i].average=(s[i].score[0]+s[i].score[1]+s[i].score[2])/3.0;
   }
   printf("原始成绩报表\n");
   print(s);
   sort(s);
   printf("排序之后的成绩报表\n");
   print(s);
   printf("前五名成绩报表\n");
   printtopfive(s);
   getch();
}
 

void sort( struct student stu[ ] ) /* 函数, 选择排序 */
{
  int i,k,j;
  struct student t;
  for(i=0;i<N-1;i++)
  {
    k=i;
    for(j=i+1;j<N;j++)
    {
      if(stu[k].average<stu[j].average)
            k=j;
      if(k!=i)
      {
       t=stu[i];  stu[i]=stu[k];  stu[k]=t;
      }
    }

   }
}

void print( struct student stu[ ] )  /* 函数, 输出 */
{
 int i;
 printf("Student ID  Student Name   Score1  Score2  Score3  Average\n");
 for(i=0;i<N;i++)
   printf("%-10d%-12s%8d%8d%8d%8.1f\n",stu[i].num,stu[i].name,
   stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].average);
}

void printtopfive( struct student stu[ ] )  /* 函数,输出前5名 */
{
 int i;
 printf("Student Name    Average\n");
 for(i=0;i<5;i++)
   printf("%-12s%8.1f\n",stu[i].name,stu[i].average);
}

posted @ 2008-04-19 20:45  emanlee  阅读(3109)  评论(1编辑  收藏  举报