C語言程式設計 練習題參考答案 第六章 (1) 結構體 綜合練習

來源:互聯網
上載者:User

 /*  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);
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.