BeautifulMan

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            16 隨筆 :: 0 文章 :: 0 評論 :: 0 Trackbacks
          復習題
          1、以下模板有什么錯誤?
          structure {
              char itable;
              int num[20];
              char * togs
          }
          答:
          正確的關鍵字是struct而不是structure。模板需要在開始花括號前有一個標記或在結束花括號后有一個變量名。在*togs后面和在模板結尾處都應該有一個分號。
          2、下面是某程序的一部分。輸出會是什么?
          #include <stdio.h>

          struct house {
              float sqft;
              int rooms;
              int stories;
              char address[40];
          };
          int main(void)
          {
              struct house fruzt = {1560.0, 6, 1, "22 Spiffo Road"};
              struct house *sign;

              sign = &fruzt;
              printf("%d %d\n", fruzt.rooms, sign->stories);
              printf("%s \n", fruzt.address);
              printf("%c %c\n", sign->address[3], fruzt.address[4]);
              return 0;
          }
          答:
          6 1
          22 Spiffo Road
          S p
          3、設計一個結構模板,保存一個月份名、一個3個字母的該月份的縮寫、該月的天數,以及月份號。
          答:
          struct month {
              char name[30];
              char sup_name[4];
              int days;
              int month_day;
          };
          4、定義一個含有12個第3題中那種類型的結構的數組,并把它初始化為一個年份(非閏年)
          答:
          struct month months[12] =
              {
                  {"January", "jan", 31, 1},
                  {"February", "feb", 28, 2},
                  {"March", "mar", 31, 3},
                  {"April", "apr", 30, 4},
                  {"May", "may", 31, 5},
                  {"June", "jun", 30, 6},
                  {"July", "jul", 31, 7},
                  {"August", "aug", 31, 8},
                  {"September", "sep", 30, 9},
                  {"October", "oct", 31, 10},
                  {"November", "nov", 30, 11},
                  {"December", "dec", 31, 12}
              };
          5、編寫一個函數。當給出月份號后,程序返回一年中到該月為止(包括該月)總共的天數。假定在外部聲明了第3題中的結構模板和一個該結構的數組。
          答:
          #include <stdio.h>

          struct month {
              char name[30];
              char sup_name[4];
              int days;
              int month_day;
          };
          int days(const struct month months[], int month);
          int main(void)
          {
              int month;
              struct month months[12] =
              {
                  {"January", "jan", 31, 1},
                  {"February", "feb", 28, 2},
                  {"March", "mar", 31, 3},
                  {"April", "apr", 30, 4},
                  {"May", "may", 31, 5},
                  {"June", "jun", 30, 6},
                  {"July", "jul", 31, 7},
                  {"August", "aug", 31, 8},
                  {"September", "sep", 30, 9},
                  {"October", "oct", 31, 10},
                  {"November", "nov", 30, 11},
                  {"December", "dec", 31, 12}
              };
              printf("Please enter the month: \n");
              scanf("%d", &month);
              printf("the total days is: %d\n", days(months, month));
              return 0;
          }
          int days(const struct month months[], int month)
          {
              int index, total;

              if(month < 1 || month > 12)
                   return -1;
              else
              {
                  for(index = 0; index < month; index++)
                       total += months[index].days;
                  return total;
              }
          }
          6、
          a.給定下面的typedef,聲明一個10個元素的指定結構的數組。然后通過各個成員賦值(或等價字符串),使第3個元素描述一個焦距長度為500mm,孔徑為f/2.0的Remarkatar鏡頭。
          typedef struct lens {     /* 鏡頭描述 */
              float foclen;         /* 焦距長度 */
              float fstop;          /* 孔徑 */
              char brand[30];       /* 品牌名稱 */
          } LENS;
          b.重復a,但在聲明中使用一個指定初始化項目列表,而不是對每個成員使用單獨的賦值語句。
          答:
          a.
              typedef struct lens {     /* 鏡頭描述 */
              float foclen;         /* 焦距長度 */
              float fstop;          /* 孔徑 */
              char brand[30];       /* 品牌名稱 */
              } LENS;
              LENS arr[10];
              arr[2].foclen = 500;
              arr[2].fstop = 2.0;
              strcpy(arr[2].brand, "Remarkatar");  // #include <string.h>
          b.
              typedef struct lens {     /* 鏡頭描述 */
              float foclen;         /* 焦距長度 */
              float fstop;          /* 孔徑 */
              char brand[30];       /* 品牌名稱 */
              } LENS;
              LENS arr[10] = { [2] = {500, 2.0, "Remarkatar"} };
          7、考慮下面的程序段:
          struct name {
              char first[20];
              char last[20];
          };
          struct bem {
              int limbs;
              struct name title;
              char type[30];
          };
          struct bem * pb;
          struct bem deb = {
              6,
              {"Berbnazel", "Gwolkapwolk"},
              "Arcturan"
          };

          pb = &deb;
          a.下列每個語句會打印出什么?
          printf("%d\n", deb.limbs);
          printf("%s\n", pb->type);
          printf("%s\n", pb->type + 2);
          b.
          怎樣用結構符號表示"Gwolkapwolk"(使用兩種方法)?
          c.
          編寫一個函數,以一個bem結構的地址作為參數,并以下面所示的形式輸出結構內容。假定結構模板在一個名為starfolk.h的文件中。
          Berbnazel Gwolkapwolk is a 6-limbed Arcturan.
          答:
          a.
          6
          Arcturan
          cturan
          b.
          deb.title.last
          pb->title.last
          c.
          #include <stdio.h>
          #include "starfolk.h"
          struct name {
              char first[20];
              char last[20];
          };
          struct bem {
              int limbs;
              struct name title;
              char type[30];
          };
          void show(const struct bem *);
          int main(void)
          {
              struct bem * pb;
              struct bem deb = {
                  6,
                  {"Berbnazel", "Gwolkapwolk"},
                  "Arcturan"
              };

              pb = &deb;
              show(pb);
              return 0;
          }
          void show(const struct bem * fp)
          {
              printf("%s %s is a %d-limbed %s.", fp->title.first, fp->title.last, fp->limbs, fp->type);
          }
          8、考慮下列聲明:
          struct fullname {
              char fname[20];
              char lname[20];
          };
          struct bard {
              struct fullname name;
              int born;
              int died;
          };
          struct bard willie;
          struct bard *pt = &willie;
          a.使用willie標識符表示willie結構的born成員。
          b.使用pt標識符表示willie結構的born成員。
          c.使用一個scanf()函數調用為通過willie標識符表示的born成員讀入一個值。
          d.使用一個scanf()函數調用為通過pt標識符表示的born成員讀入一個值。
          e.使用一個scanf()函數調用為通過willie標識符表示的name成員的lname成員讀入一個值。
          f.使用一個scanf()函數調用為通過pt標識符表示的name成員的lname成員讀入一個值。
          g.構造一個標識符,表示willie變量描述的人的名字的第3個字母。
          h.構造一個表達式,表示willie變量描述的人的姓和名的所有字母數。
          答:
          a.willie.born
          b.pt->born
          c.scanf("%d", &willie.born);
          d.scanf("%d", &pt->born);
          e.scanf("%s", willie.name.lname);
          f.scanf("%s", pt->name.lname);
          g.willie.name.fname[2];  (我覺得有欠考慮,萬一姓不足3個字母怎么辦?)
          h.strlen(willie.name.fname) + strlen(willie.name.lname);
          9、定義一個適合保存下列項目的結構模板:一輛汽車的名稱、馬力、市內行駛的EPA英里每加侖(mpg)等級、軸距和使用年數。用car作為模板標記。
          答:(參考課后答案)
          下面是一種可能性:
          struct car {
              char name[20];
              float hp;
              float epampg;
              float wbase;
              int year;
          };
          10、假設有以下結構:
          struct gas {
              float distance;
              float gals;
              float mpg;
          };
          a.設計一個函數,它接受一個struct gas參數。假定傳遞進來的結構包括distance和gals信息。函數為mpg成員正確計算出值并返回這個現在完整的結構。
          b.設計一個函數,它接受一個struct gas參數的地址。假定傳遞進來的結構包括distance和gals信息。函數為mpg成員正確計算出值并把它賦給恰當的成員。
          答:
          a.
          struct gas function1(struct gas fp)
          {
              if(fp.gals > 0)
                  fp.mpg = fp.distance / fp.gals;
              else
                  fp.mpg = -1.0;
              return fp;
          }
          b.
          void function1(struct gas * fp)
          {
              if(fp->gals > 0)
                  fp->mpg = fp->distance / fp->gals;
              else
                  fp->mpg = -1.0;
          }
          11、聲明一個枚舉類型,使用choices作為標記,將枚舉常量no、yes和maybe分別設置為0、1和2。
          答:enum choices {no, yes, maybe};
          12、聲明一個指向函數的指針。該函數的返回值是一個char指針,參數為一個char指針和一個char值。
          答:
          char * (* fp)(char *, char);
          13、聲明4個函數,并把一個指針數組初始化為指向它們。每個函數接受兩個double參數并返回一個double值。
          答:
          double f1(doubledouble);
          double f2(doubledouble);
          double f3(doubledouble);
          double f4(doubledouble);
          double (*fp[4])(doubledouble) = {f1, f2, f3, f4};
          編程練習
          1、
          #include <stdio.h>
          #include <string.h>
          #define LEN 12
          struct month {
              char name[30];
              char abbreviation[4];
              int days;
              int month_no;
          };
          const struct month months[LEN] =
          {
              {"January", "jan", 31, 1},
              {"February", "feb", 28, 2},
              {"March", "mar", 31, 3},
              {"April", "apr", 30, 4},
              {"May", "may", 31, 5},
              {"June", "jun", 30, 6},
              {"July", "jul", 31, 7},
              {"August", "aug", 31, 8},
              {"September", "sep", 30, 9},
              {"October", "oct", 31, 10},
              {"November", "nov", 30, 11},
              {"December", "dec", 31, 12}
          };
          int total_day(char * str);
          int main(void)
          {
              char month_name[10];

              printf("Please enter the month name: \n");
              while(gets(month_name) != NULL && month_name[0] != '\0')
              {
                  if(total_day(month_name))
                      printf("In a year the total number of days to %s is %d\n", month_name, total_day(month_name));
                  else
                      printf("You entered is not a month name\n");
                  printf("Please enter the month name: \n");
              }

              return 0;
          }
          int total_day(char * str)
          {
              int i, index;
              int total = 0;
              for(i = 0; i < LEN; i++)
              {
                  if(strcmp(str, months[i].abbreviation) == 0)
                  {
                      index = i;
                      for(i = 0, total = 0; i <= index; i++)
                          total += months[i].days;
                      break;
                  }
              }
              return total;
          }
          第二次修改,如果輸入月份名正確,立即輸出天數;如果輸入月份名不正確,會循環讓繼續輸入,直到輸入正確為止。不過代碼量減少很多:
          #include <stdio.h>
          #include <stdlib.h>
          #include <string.h>

          struct month {
              char name[31];
              char abbreviation[11];
              int days;
              int month_of_year;
          };
          int main(void)
          {
              int total = 0;
              int index = 0;
              char name[31];
              struct month months[12] = {
                  {"January", "jan", 31, 1},
                  {"February", "feb", 28, 2},
                  {"March", "mar", 31, 3},
                  {"April", "apr", 30, 4},
                  {"May", "may", 31, 5},
                  {"June", "jun", 30, 6},
                  {"July", "jul", 31, 7},
                  {"August", "aug", 31, 8},
                  {"September", "sep", 30, 9},
                  {"October", "oct", 31, 10},
                  {"November", "nov", 30, 11},
                  {"December", "dec", 31, 12}
              };

              puts("請輸入月份名(輸入空行結束):");
              while(gets(name) != NULL && name[0] != '\0')
              {
                  for(int i = 0; i < 12; i++)
                      if(strcmp(name, months[i].name) == 0)
                      {
                          index = i;
                          for(int i = 0; i <= index; i++)
                              total += months[i].days;
                          printf("一年中截止到%d月為止(包括該月)總共的天數為:%d", months[index].month_of_year, total);
                          exit(0);
                      }
                  puts("您所輸入的不是月份名,請您重新輸入(輸入空行結束):");
              }
              return 0;
          }

          2、(大家來來看看,寫的怎么樣啊!)
          #include <stdio.h>
          #include <string.h>
          #define LEN 12
          struct month {
              char name[30];
              char abbreviation[4];
              int days;
              int month_no;
          };
          const struct month months[LEN] =
          {
              {"January", "jan", 31, 1},
              {"February", "feb", 28, 2},
              {"March", "mar", 31, 3},
              {"April", "apr", 30, 4},
              {"May", "may", 31, 5},
              {"June", "jun", 30, 6},
              {"July", "jul", 31, 7},
              {"August", "aug", 31, 8},
              {"September", "sep", 30, 9},
              {"October", "oct", 31, 10},
              {"November", "nov", 30, 11},
              {"December", "dec", 31, 12}
          };
          int total_day(int month);
          void eatline(void);
          int main(void)
          {
              int year;
              int day;
              int month;
              int total_mon, total;
              printf("Please enter a year(q to quit): \n");
              while(scanf("%d", &year) == 1 && year >= 1971 && year <= 9999)
              {
                  printf("Please enter the month name: \n");
                  while(scanf("%d", &month) != 1 || month < 1 || month > 12)
                  {
                      printf("The number of months you entered does not meet the requirements.\n");
                      printf("Please again enter a month: \n");
                      eatline();
                  }
                  total_mon = total_day(month);
                  printf("Please enter a day: \n");
                  while(scanf("%d", &day) != 1 || day < 1 || day > 31)
                  {
                      printf("The number of days you entered does not meet the requirements.\n");
                      printf("Please again enter a day: \n");
                      eatline();
                  }
                  total = day + total_mon;
                  printf("The total number of days in a year to a given day is %d\n", total);
                  printf("Please enter a year(q to quit): \n");
              }
              printf("Done.\n");
              return 0;
          }
          int total_day(int month)
          {
              int i;
              int total = 0;
              if(month > 1)
                  for(i = 0; i < month - 1; i++)
                      total += months[i].days;
              return total;
          }
          void eatline(void)
          {
              while(getchar() != '\n')
                  continue;
          }
          第二次修改如下,感覺越改越麻煩了,但也可以正常運行!
          #include <stdio.h>
          #include <stdlib.h>
          #include <string.h>

          void eatline(void);
          struct month {
              char name[31];
              char abbreviation[11];
              int days;
              int month_of_year;
          };
          int main(void)
          {
              int total = 0;
              int index = 0;
              int year, month, day, status;
              char name[31];
              struct month months[12] = {
                  {"January", "jan", 31, 1},
                  {"February", "feb", 28, 2},  // 平年
                  {"March", "mar", 31, 3},
                  {"April", "apr", 30, 4},
                  {"May", "may", 31, 5},
                  {"June", "jun", 30, 6},
                  {"July", "jul", 31, 7},
                  {"August", "aug", 31, 8},
                  {"September", "sep", 30, 9},
                  {"October", "oct", 31, 10},
                  {"November", "nov", 30, 11},
                  {"December", "dec", 31, 12}
              };

              puts("請您輸入年份:");
              status = scanf("%d", &year);
              while(status != 1 || (status == 1 && (year > 9999 || year < 1971)))
              {
                  puts("您輸入要不就是一些非數字,要不就是年份不在1971~9999之間!");
                  puts("請您重新輸入一個合法年份:");
                  eatline();
                  status = scanf("%d", &year);
              }
              puts("請您輸入月份:");
              status = scanf("%d", &month);
              while(status != 1 || (status == 1 && (month > 12 || month < 1)))
              {
                  puts("您輸入要不就是一些非數字,要不就是月份不在1~12之間!");
                  puts("請您重新輸入一個合法月份:");
                  eatline();
                  status = scanf("%d", &month);
              }
              // 輸入日數(我也不要考慮那么麻煩了,分1~28(平年)、1~29(閏年)、1~30、1~31等情況)
              puts("請您輸入日數:");
              status = scanf("%d", &day);
              while(status != 1 || (status == 1 && (day > 31 || day < 1)))
              {
                  puts("您輸入要不就是一些非數字,要不就是日數不在1~31之間!");
                  puts("請您重新輸入一個合法日數:");
                  eatline();
                  status = scanf("%d", &day);
              }
              if(month == 1)
                  printf("%d年這一年截止到%d月%d日為止總共的天數為:%d", year, month, day, day);
              else
                  for(int i = 1; i < 12; i++)
                  {
                      if(month == months[i].month_of_year)
                      {
                          index = i;
                          for(int i = 0; i <= index - 1; i++)
                              total += months[i].days;
                          printf("%d年這一年截止到%d月%d日為止總共的天數為:%d", year, month, day, total + day);
                      }
                  }
              return 0;
          }
          void eatline(void)
          {
              while(getchar() != '\n')
                  continue;
          }

          3、
          #include <stdio.h>
          #include <string.h>
          #define MAXTITL 40
          #define MAXAUTL 40
          #define MAXBKS 100
          struct book {
              char title[MAXTITL];
              char author[MAXAUTL];
              float value;
          };
          // 按照輸入的順序輸出圖書的描述
          void show(struct book *, int);
          // 按照標題的字母升序輸出圖書的描述
          void showByTitle(struct book *, int);
          // 按照value值的升序輸出圖書的描述
          void showByValue(struct book *, int);
          int main(void)
          {
              struct book library[MAXBKS];
              int count = 0;

              printf("請輸入書之標題\n");
              printf("在一行的開始處鍵入[Enter]鍵結束\n");
              while(count < MAXBKS && gets(library[count].title) != NULL
                                   && library[count].title[0] != '\0')
              {
                  printf("現在請輸入作者名\n");
                  gets(library[count].author);
                  printf("現在請輸入書價\n");
                  scanf("%f", &library[count++].value);
                  while(getchar()!= '\n')
                      continue;
                  if(count < MAXBKS)
                      printf("請輸入書之標題\n");
              }
              printf("按照輸入的順序輸出圖書的描述\n");
              show(library, count);
              showByTitle(library, count);
              showByValue(library, count);
              return 0;
          }
          void show(struct book * bklist, int count)
          {

              if(count > 0)
              {
                  for(int i = 0; i < count; i++)
                      printf("%s by %s: $%.2f\n", bklist[i].title, bklist[i].author, bklist[i].value);
              }
              else
                  printf("根本就沒輸入書!\n");
          }
          void showByTitle(struct book * bklist, int count)
          {
              printf("按照標題的字母升序輸出圖書的描述\n");
              if(count > 0)
              {
                  struct book temp;
                  for(int i = 0; i < count; i++)
                      for(int j = i + 1; j < count; j++)
                          if(strcmp(bklist[i].title, bklist[j].title) > 0)
                          {
                              temp = bklist[i];
                              bklist[i] = bklist[j];
                              bklist[j] = temp;
                          }
                  show(bklist, count);
              }
              else
                  printf("根本就沒輸入書!\n");
          }
          void showByValue(struct book * bklist, int count)
          {
              printf("按照value值的升序輸出圖書的描述\n");
              if(count > 0)
              {
                  struct book temp;
                  for(int i = 0; i < count; i++)
                      for(int j = i + 1; j < count; j++)
                          if(bklist[i].value > bklist[j].value)
                          {
                              temp = bklist[i];
                              bklist[i] = bklist[j];
                              bklist[j] = temp;
                          }
                  show(bklist, count);
              }
              else
                  printf("根本就沒輸入書!\n");
          }

          4、
          #include <stdio.h>
          #include <string.h>
          #define LEN 21
          #define NUM 5
          struct name {
              char fname[LEN];
              char mname[LEN];
              char lname[LEN];
          };
          struct person {
              char number[LEN];
              struct name person_name;
          };
          void showa(struct person *, int);
          void showb(struct person);
          int main(void)
          {
              struct person persons[NUM] = {
                  {
                      "302039823",
                      {"Dirbble", "M", "Flossie"}
                  },
                  {
                      "000039823",
                      {"Jack", "", "Flossie"}
                  },
                  {
                      "002039823",
                      {"John", "M.C", "Davis"}
                  },
                  {
                      "302039800",
                      {"John", "G.W", "Flossie"}
                  },
                  {
                      "302030000",
                      {"Dirbble", "Adam", "Wilson"}
                  }
              };
              printf("---------------------------把結構數組傳遞給函數----------------------\n");
              showa(persons, NUM);
              printf("---------------------------把結構的值傳遞給函數----------------------\n");
              for(int i = 0; i < NUM; i++)
                  showb(persons[i]);
              return 0;
          }
          void showa(struct person * per, int n)
          {
              for(int i = 0; i < n; i++)
                  if(per[i].person_name.mname[0] != '\0')
                      printf("%s, %s %c. - %s\n", per[i].person_name.fname,
                             per[i].person_name.lname, per[i].person_name.mname[0], per[i].number);
                  else
                      printf("%s, %s - %s\n", per[i].person_name.fname, per[i].person_name.lname, per[i].number);
          }
          void showb(struct person per)
          {
              if(per.person_name.mname[0] != '\0')
                  printf("%s, %s %c. - %s\n", per.person_name.fname,
                         per.person_name.lname, per.person_name.mname[0], per.number);
              else
                  printf("%s, %s - %s\n", per.person_name.fname, per.person_name.lname, per.number);
          }

          5、
          第一次就完美實現,太爽了,各位看官請看:
          #include <stdio.h>
          #include <string.h>
          #include <stdbool.h>
          #define LEN 31
          #define CSIZE 4

          struct name {
              char fname[LEN];
              char lname[LEN];
          };
          struct student {
              struct name stuname;
              double scores[3];
              double average;
          };
          // 請求用戶輸入學生姓名和分數
          void input_scores(struct student *);
          // 為每個結構計算平均分
          void calculate(struct student *);
          // 輸出每個結構的信息
          void show(struct student *);
          // 輸出結構的每個數值成員的班級平均分
          void calcu_average(struct student *);
          int main(void)
          {
              struct student students[CSIZE] = {
                  { .stuname = {"Ye", "Leilei"} },
                  { .stuname = {"Li", "Ayun"} },
                  { .stuname = {"Gao", "Hang"} },
                  { .stuname = {"Yan", "Congcong"} }
              };
              input_scores(students);
              calculate(students);
              printf("-------------------------------------------------------------------------\n");
              show(students);
              printf("-------------------------------------------------------------------------\n");
              calcu_average(students);
              return 0;
          }
          void input_scores(struct student * stu)
          {
              char stu_name[LEN];
              char name[LEN];
              bool isExit = false;
              int count = 1;

              printf("請輸入第%d個學生的姓名:\n", count);
              while(count < 5 && gets(stu_name) != NULL)
              {
                  for(int i = 0; i < CSIZE; i++)
                  {
                       strcpy(name, stu[i].stuname.fname);
                       strcat(name, stu[i].stuname.lname);
                       if(strcmp(stu_name, name) == 0)
                       {
                           isExit = true;
                           printf("請輸入學生分數(3個):\n");
                           for(int j = 0; j < 3; j++)
                           {
                               printf("請輸入第%d個分數:\n", j + 1);
                               scanf("%lf", &stu[i].scores[j]);
                           }
                           break;
                       }
                  }

                  if(isExit)
                  {
                      while(getchar() != '\n')
                           continue;
                      if(count < 4)
                          printf("請輸入第%d個學生的姓名:\n", ++count);
                      else
                          ++count;
                      isExit = false;
                  }
                  else
                  {
                      printf("您輸入的學生姓名不存在!!!\n");
                      printf("請重新輸入學生姓名:\n");
                  }
              }
          }
          void calculate(struct student * stu)
          {
              double tot;

              for(int i = 0; i < CSIZE; i++)
              {
                  tot = 0.0;
                  for(int j = 0; j < 3; j++)
                      tot += stu[i].scores[j];
                  stu[i].average = tot / 3;
              }
          }
          void show(struct student * stu)
          {
              for(int i = 0; i < CSIZE; i++)
                  printf("學生%s%s的3門分數分別為:%.2f, %.2f %.2f, 所得平均分為:%.2f\n",
                         stu[i].stuname.fname, stu[i].stuname.lname,
                         stu[i].scores[0], stu[i].scores[1], stu[i].scores[2], stu[i].average);
          }
          void calcu_average(struct student * stu)
          {
              double tot;
              for(int i = 0; i < 3; i++)
              {
                  tot = 0.0;
                  printf("第%d個數值的班級平均分為:", i + 1);
                  for(int j = 0; j < CSIZE; j++)
                      tot += stu[j].scores[i];
                  printf("%.2f\n", tot / CSIZE);

              }
          }

          6、借鑒(30歲學編程http://xiongyi85.blog.51cto.com/8756903/1660546前輩的做法,定有不妥之處)
          #include <stdio.h>
          #include <string.h>
          #include <stdlib.h>
          #define LEN 19
          #define SIZE 31

          struct athlete {
              int index;         // 球員號碼
              char lname[SIZE];  // 名
              char fname[SIZE];  // 姓
              int play_times;    // 上場次數
              int hit_numbers;   // 擊中數
              int base_numbers;  // 走壘數
              int rbi;           // 跑點數
              double success_rate; // 擊球平均成功率
          };
          // 計算每個球員的擊球平均成功率
          void calcu(struct athlete *, int);
          // 顯示每個球員的累計數據
          void show(struct athlete *, int);
          // 對整個時期顯示一行綜合統計數據
          void show_statistical_data(struct athlete *, int);
          int main(void)
          {
              struct athlete athletes[LEN] = {
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0},
                  {0, "", "", 0, 0, 0, 0, 0.0}
              };
              struct athlete temp; // 臨時結構
              FILE *fp;
              char file[SIZE];
              int index;

              // 讀取Bangqiu文本文件
              puts("請輸入要讀取的文本文件:");
              gets(file);
              if((fp = fopen(file, "r")) == NULL)
              {
                  fprintf(stderr, "不能打開文件%s\n", file);
                  exit(EXIT_FAILURE);
              }
              // 把Bangqiu文本文件的數據存儲到一個結構數組中
              while(fscanf(fp, "%d %s %s %d %d %d %d", &index, temp.lname, temp.fname,
                               &temp.play_times, &temp.hit_numbers, &temp.base_numbers, &temp.rbi) == 7)
              {
                  if(strcmp(athletes[index].fname, temp.fname) != 0)
                      strcpy(athletes[index].fname, temp.fname);
                  if(strcmp(athletes[index].lname, temp.lname) != 0)
                      strcpy(athletes[index].lname, temp.lname);
                  athletes[index].play_times += temp.play_times;
                  athletes[index].hit_numbers += temp.hit_numbers;
                  athletes[index].base_numbers += temp.base_numbers;
                  athletes[index].rbi += temp.rbi;
              }
              calcu(athletes, LEN);
              show(athletes, LEN);
              show_statistical_data(athletes, LEN);
              return 0;
          }
          void calcu(struct athlete * ath, int n)
          {
              for(int i = 0; i < n; i++)
                  ath[i].success_rate = (double)ath[i].hit_numbers / ath[i].play_times;
          }
          void show(struct athlete * ath, int n)
          {
              for(int i = 0; i < n; i++)
              {
                  printf("球員%s%s的累計數據為:\n", ath[i].fname, ath[i].lname);
                  printf("上場次數:%d\n", ath[i].play_times);
                  printf("擊中數:%d\n", ath[i].hit_numbers);
                  printf("走壘數:%d\n", ath[i].base_numbers);
                  printf("跑點數:%d\n", ath[i].rbi);
                  printf("擊球平均成功率:%.2f%%\n", ath[i].success_rate * 100);
                  if(i < 18)
                      printf("********************************\n");
              }
          }
          void show_statistical_data(struct athlete * ath, int n)
          {
              struct athlete temp = {
                  {0, "", "", 0, 0, 0, 0, 0.0}
              };

              for(int i = 0; i < n; i++)
              {
                  temp.play_times += ath[i].play_times;
                  temp.hit_numbers += ath[i].hit_numbers;
                  temp.base_numbers += ath[i].base_numbers;
                  temp.rbi += ath[i].rbi;
              }
              printf("**********************綜合統計數據*******************************\n");
              printf("所有球員的上場次數總和為:%d\n", temp.play_times);
              printf("擊中數總和為:%d\n", temp.hit_numbers);
              printf("走壘數總和為:%d\n", temp.base_numbers);
              printf("跑點數總和為:%d\n", temp.rbi);
              printf("擊球平均成功率為:%.2f%%", (double)temp.hit_numbers / temp.play_times * 100);
          }

          7、(太屌了,搞了一上午了,終于可以跑起來了,借鑒http://ptgmedia.pearsoncmg.com/images/9780321928429/downloads/9780321928429_ProgrammingExerciseAnswers_Selected.pdf)
          #include <stdio.h>
          #include <string.h>
          #include <stdlib.h>
          #include <stdbool.h>
          #define MAXTITL 40
          #define MAXAUTL 40
          #define MAXBKS 10

          struct book {
              char title[MAXTITL];
              char author[MAXAUTL];
              float value;
          };
          struct pack {
              struct book book;
              bool delete_me;
          };
          // 刪除或修改該記錄的選擇
          int getlet(const char *);
          // 修改該記錄
          void update(struct pack *);
          // 從鍵盤獲得輸入
          char * s_gets(char *, int);

          int getbook(struct pack *);

          int main(void)
          {
              struct pack library[MAXBKS];
              int count = 0;
              int deleted = 0;
              int index, filecount, open;
              FILE * pbooks;
              int size = sizeof(struct book);

              if((pbooks = fopen("book.dat", "r")) != NULL)
              {
                  while(count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1)
                  {
                      if(count == 0)
                          puts("Current contents of book.dat: ");
                      printf("%s by %s: $%.2f\n", library[count].book.title, library[count].book.author, library[count].book.value);
                      printf("Do you wish to change or delete this entry?<y/n> ");
                      if(getlet("yn") == 'y')
                      {
                          printf("Enter c to change, d to delete this entry.<c/d> ");
                          if(getlet("cd") == 'd')   // 刪除該記錄(并不立即實現該功能)
                          {
                              library[count].delete_me = true;
                              deleted++;
                              puts("Entry marked for deletion.");
                          }
                          else
                              update(&library[count]); // 修改該記錄(修改要比刪除簡單)
                      }
                      count++;
                  }
                  fclose(pbooks);
              }

              filecount = count - deleted;
              if(count == MAXBKS)
              {
                  fputs("The book.dat file is full.", stderr);
                  exit(1);
              }
              puts("Please add new book titles.");
              puts("Press [enter] at the start of a line to stop.");
              open = 0;
              while(filecount < MAXBKS)
              {
                  if(filecount < count)
                  {
                      while(library[open].delete_me == false)
                          open++;
                      if(getbook(&library[open]) == 1)
                          break;
                  }
                  else if(getbook(&library[filecount]) == 1)
                      break;
                  filecount++;
                  if(filecount < MAXBKS)
                      puts("Enter the new book title.");
              }
              puts("Here is the list of your books: ");
              for(index = 0; index < filecount; index++)  // 此處應該為count
                  if(library[index].delete_me == false)
                      printf("%s by %s: $%.2f\n", library[index].book.title, library[index].book.author, library[index].book.value);
              if((pbooks = fopen("book.dat", "w")) == NULL)
              {
                  puts("Can't open book.dat file for output.");
                  exit(2);
              }
              for(index = 0; index < filecount; index++)  // 此處應該為count
                  if(library[index].delete_me == false)
                      fwrite(&(library[index].book), size, 1, pbooks);
              puts("Bye.\n");
              fclose(pbooks);
              return 0;
          }
          int getlet(const char * s)
          {
              char c;

              c = getchar();
              while(strchr(s, c) == NULL)
              {
                  printf("Enter the characters in the list %s\n", s);
                  while(getchar() != '\n')
                      continue;
                  c = getchar();
              }
              while(getchar() != '\n')
                  continue;
              return c;
          }
          int getbook(struct pack * item)
          {
              int status = 0;

              if(s_gets(item->book.title, MAXTITL) == NULL || item->book.title[0] == '\0')
                  status = 1;
              else
              {
                  printf("Now enter the author: ");
                  s_gets(item->book.author, MAXAUTL);
                  printf("Now enter the value: ");
                  while(scanf("%f", &item->book.value) != 1)
                  {
                      puts("Please use numeric input");
                      scanf("%*s");
                  }
                  while(getchar() != '\n')
                      continue;
                  item->delete_me = false;
              }
              return status;
          }
          void update(struct pack * item)
          {
              struct book copy;
              char c;

              copy = item->book;
              puts("Enter the letter that indicates your choice: ");
              puts("t) modify title       a) modify author");
              puts("v) modify value       s) quit, saving changes");
              puts("q) quit, ignore changes");
              while((c = getlet("tavsq")) != 's' && c != 'q')
              {
                  switch(c)
                  {
                      case 't': puts("Enter new title: ");
                                s_gets(copy.title, MAXTITL);
                                break;
                      case 'a': puts("Enter new author: ");
                                s_gets(copy.author, MAXAUTL);
                                break;
                      case 'v': puts("Enter new value: ");
                                while(scanf("%f", &copy.value) != 1)
                                {
                                    puts("Enter a numeric value: ");
                                    scanf("%*s");  // *放在%和說明符之間,使得函數跳過相應的輸入項目
                                }
                                while(getchar() != '\n')
                                    continue;
                                break;
                  }
                  puts("t) modify title       a) modify author");
                  puts("v) modify value       s) quit, saving changes");
                  puts("q) quit, ignore changes");
              }
              if(c == 's')
                  item->book = copy;
          }
          char * s_gets(char * st, int n)
          {
              char * ret_val;
              char * find;

              ret_val = fgets(st, n, stdin);
              if(ret_val)
              {
                  find = strchr(ret_val, '\n');
                  if(find)
                      *find = '\0';
                  else
                      while(getchar() != '\n')
                          continue;
              }
              return ret_val;
          }
          運行效果圖如下:


          8、(肯定還有很多不如意的地方,但程序起碼能跑起來)
          #include <stdio.h>
          #include <string.h>
          #include <stdlib.h>
          #include <stdbool.h>
          #define SIZE 21
          #define MAXBKS 12

          struct seat {
              char number[SIZE];
              bool allotted;
              char fname[SIZE];
              char lname[SIZE];
          };

          int getlet(const char *);
          void showMenu(struct seat * st);

          void showa(struct seat * st, int n);
          void showb(struct seat * st, int n);
          void showc(struct seat * st, int n);
          void assign(struct seat * st, int n);
          void deletes(struct seat * st, int n);

          int main(void)
          {
              struct seat seats[MAXBKS] = {
                  {"XS10000", true, "Li", "Ayun"},
                  {"XS10011", false, "", ""},
                  {"XS10002", false, "", ""},
                  {"XS10003", false, "", ""},
                  {"XS10004", false, "", ""},
                  {"XS10005", false, "", ""},
                  {"XS10006", true, "Gao", "Hang"},
                  {"XS10007", false, "", ""},
                  {"XS10008", false, "", ""},
                  {"XS10009", false, "", ""},
                  {"XS10010", false, "", ""},
                  {"XS10001", false, "", ""}
              };
              int count = 0;
              FILE * pbooks;
              int size = sizeof(struct seat);

              if((pbooks = fopen("seat.dat", "w")) == NULL)
              {
                  fprintf(stderr, "Can't open seat.dat file.\n");
                  exit(EXIT_FAILURE);
              }
              // 程序每次運行時,首先從文件中載入數據
              rewind(pbooks);
              while(count < MAXBKS && fread(&seats[count], size, 1, pbooks) == 1)
                  count++;

              showMenu(seats);

              for(int index = 0; index < count; index++)
                  fwrite(&seats[index], size, 1, pbooks);
              puts("Bye.\n");
              fclose(pbooks);
              return 0;
          }
          int getlet(const char * s)
          {
              char c;

              c = getchar();
              while(strchr(s, c) == NULL)
              {
                  printf("Enter the characters in the list %s\n", s);
                  while(getchar() != '\n')
                      continue;
                  c = getchar();
              }
              while(getchar() != '\n')
                  continue;
              return c;
          }
          void showMenu(struct seat * seats)
          {
              char c;

              puts("To choose a function, enter its letter label: ");
              puts("a) Show number of empty seats");
              puts("b) Show list of empty seats");
              puts("c) Show alphabetical list of seats");
              puts("d) Assign a customer to a seat assignment");
              puts("e) Delete a seat assignment");
              puts("f) Quit");
              while((c = getlet("abcdef")) != 'f')
              {
                  switch(c)
                  {
                      case 'a': showa(seats, MAXBKS);
                                break;
                      case 'b': showb(seats, MAXBKS);
                                break;
                      case 'c': showc(seats, MAXBKS);
                                break;
                      case 'd': assign(seats, MAXBKS);
                                break;
                      case 'e': deletes(seats, MAXBKS);
                                break;
                  }
                  puts("To choose a function, enter its letter label: ");
                  puts("a) Show number of empty seats");
                  puts("b) Show list of empty seats");
                  puts("c) Show alphabetical list of seats");
                  puts("d) Assign a customer to a seat assignment");
                  puts("e) Delete a seat assignment");
                  puts("f) Quit");
              }
          }
          // 顯示空座位(未分配)的數量
          void showa(struct seat * st, int n)
          {
              int num = 0;

              for(int i = 0; i < n; i++)
                  if(st[i].allotted == false)
                      num++;
              printf("空座位數為: %d\n", num);
          }
          // 顯示空座位的詳細信息列表
          void showb(struct seat * st, int n)
          {
              printf("還未分配出去的座位編號: \n");
              for(int i = 0; i < n; i++)
                  if(st[i].allotted == false)
                      printf("%s\n", st[i].number);
          }
          // (編號)按字母順序排列的座位
          void showc(struct seat * st, int n)
          {
              struct seat temp;

              printf("按字母順序排列的座位: \n");
              for(int i = 0; i < n - 1; i++)
                  for(int j = i + 1; j < n; j++)
                      if(strcmp(st[i].number, st[j].number) > 0)
                      {
                          temp = st[i];
                          st[i] = st[j];
                          st[j] = temp;
                      }
              for(int i = 0; i < n; i++)
                  if(st[i].allotted == false)
                      printf("編號為%s的座位還未售出\n", st[i].number);
                  else
                      printf("編號為%s的座位已售出,持有人是%s%s\n", st[i].number, st[i].fname, st[i].lname);
          }
          // 售票
          void assign(struct seat * st, int n)
          {
              int empty = 0;

              while(empty < n)
              {
                  if(st[empty].allotted == false)
                  {
                      puts("請輸入您的姓: ");
                      gets(st[empty].fname);
                      if(st[empty].fname[0] == '\0')
                          break;
                      puts("請輸入您的名: ");
                      gets(st[empty].lname);
                      if(st[empty].lname[0] == '\0')
                          break;
                      st[empty].allotted =true;
                      printf("%s%s已成功購買到票!\n", st[empty].fname, st[empty].lname);
                  }
                  empty++;
              }
          }
          // 退票 (按姓名退票功能太簡單,因為可能許多人同名,暫且這樣)
          void deletes(struct seat * st, int n)
          {
              bool found = false;
              char f_name[SIZE];
              char l_name[SIZE];

              puts("請輸入您的姓: ");
              while(gets(f_name) != NULL && f_name[0] != '\0')
              {
                  puts("請輸入您的名: ");
                  gets(l_name);
                  if(l_name[0] == '\0')
                      break;
                  for(int i = 0; i < n; i++)
                      if(strcmp(st[i].fname, f_name) == 0 && strcmp(st[i].lname, l_name) == 0 )
                      {
                          st[i].allotted = false;
                          found = true;
                          printf("%s%s已成功退票!\n", f_name, l_name);
                      }
                  if(found)
                      puts("請輸入您的姓: ");
                  else
                  {
                      printf("不好意思,%s%s,您還未定票!\n", f_name, l_name);
                      break;
                  }
              }
          }
          運行效果圖太大,所以沒貼上了!!!
          第二次更新如下:(完美實現,借鑒http://ptgmedia.pearsoncmg.com/images/9780321928429/downloads/9780321928429_ProgrammingExerciseAnswers_Selected.pdf的做法)
          #include <stdio.h>
          #include <string.h>
          #include <stdlib.h>
          #define LEN 14
          #define EMPTY 0
          #define TAKEN 1
          #define CONTINUE 1
          #define DONE 0
          #define SEATS 12
          #define CHOICES 6

          struct planestats {
              int seat_id;
              int status;
              char last[LEN];
              char first[LEN];
          };

          int getmenu(void);
          int getlet(const char *);
          int openings(const struct planestats *, int);
          void show_empties(const struct planestats *, int);
          void makelist(const struct planestats *, char *, int);
          void list_assgin(struct planestats *[], int);
          void sort(struct planestats *[], int);
          void assign_seat(struct planestats *, int);
          void delete_seat(struct planestats *, int);
          void show_seat(const struct planestats *, int);
          char * s_gets(char *, int);

          int main(void)
          {
              struct planestats plane_1[SEATS], *ps[SEATS];
              int choice;
              int i;
              FILE *fp;
              size_t size = sizeof(struct planestats);

              for(i = 0; i < SEATS; i++)
                  ps[i] = &plane_1[i];
              /* 若文件air.dat打不開,則初始化結構數組 */
              if((fp = fopen("air.dat", "rb")) == NULL)
              {
                  for(i = 0; i < SEATS; i++)
                  {
                      plane_1[i].status = EMPTY;
                      plane_1[i].seat_id = i + 1; // 編號從1開始
                  }
              }
              else
              {
                  fread(plane_1, size, SEATS, fp); // 一次寫入結構數組plane_1中
                  fclose(fp);
              }
              while((choice = getmenu()) != 'q')
              {
                  switch(choice)
                  {
                      case 'o': printf("There are %d empty seats.\n",
                                openings(plane_1, SEATS));
                                break;
                      case 'e': show_empties(plane_1, SEATS);
                                break;
                      case 'l': list_assgin(ps, SEATS);
                                break;
                      case 'a': assign_seat(plane_1, SEATS);
                                break;
                      case 'd': delete_seat(plane_1, SEATS);
                                break;
                  }
              }
              if((fp = fopen("air.dat", "wb")) == NULL)
                  puts("Can't save data to file.");
              else
              {
                  fwrite(plane_1, size, SEATS, fp); // 將結構數組一次寫入到文件中
                  fclose(fp);
              }
              puts("Bye from Colossus Airlines!");
              return 0;
          }
          int getmenu(void)
          {
              const char * descript[CHOICES] = {
                  "Show number of empty seats",
                  "Show list of empty seats",
                  "Show alphabetical list of seats",
                  "Assign a customer to a seat assignment",
                  "Delete a seat assignment",
                  "Quit"
              };
              const char labels[CHOICES + 1] = "oeladq";
              int i;

              puts("To choose a function, enter its letter label: ");
              for(i = 0; i < CHOICES; i++)
                  printf("%c) %s\n", labels[i], descript[i]);
              return getlet(labels);
          }
          int getlet(const char * s)
          {
              char c;

              c= getchar();
              while(strchr(s, c) == NULL)
              {
                  printf("Enter a character in the list %s\n", s);
                  while(getchar() != '\n')
                      continue;
                  c = getchar();
              }
              while(getchar() != '\n')
                  continue;
              return c;
          }
          int openings(const struct planestats * pl, int n)
          {
              int count = 0;
              int seat;

              for(seat = 0; seat < n; seat++)
                  if(pl[seat].status == EMPTY)
                      count++;
              return count;
          }
          void show_empties(const struct planestats * pl, int n)
          {
              char seating[3 * SEATS];

              if(openings(pl, n) == 0)
                  printf("All seats are assigned\n");
              else
              {
                  puts("The following seats are available: ");
                  makelist(pl, seating, EMPTY);
                  puts(seating);
              }
          }
          void makelist(const struct planestats * pl, char * str, int kind)
          {
              int seat;
              char temp[LEN];

              str[0] = '\0';
              for(seat = 0; seat < SEATS; seat++)
                  if(pl[seat].status == kind)
                  {
                      sprintf(temp, " %d", pl[seat].seat_id); // 把格式化輸出寫到指定的字符串中
                      strcat(str, temp);
                  }
          }
          void list_assgin(struct planestats *ps[], int n)
          {
              int i;

              if(openings(*ps, n) == n)
                  puts("All seats are empty.");
              else
              {
                  sort(ps, n);
                  for(i = 0; i < n; i ++)
                      if(ps[i]->status == TAKEN)
                          printf("Seat %d: %s, %s\n", ps[i]->seat_id, ps[i]->last, ps[i]->first);
              }
          }
          void sort(struct planestats *array[], int n)
          {
              int top, search;
              struct planestats * temp;

              for(top = 0; top < n - 1; top++)
                  for(search = top + 1; search < n; search++)
                  if(strcmp(array[top]->last, array[search]->last) > 0)
                  {
                      temp = array[top];
                      array[top] = array[search];
                      array[search] = temp;
                  }
          }
          void assign_seat(struct planestats * pl, int n)
          {
              char list[3 * SEATS];
              int seat, loop;

              if(openings(pl, n) == 0)
                  puts("All seats are assigned.");
              else
              {
                  makelist(pl, list, EMPTY);
                  puts("Which seat do you want? Choose from the list: ");
                  puts(list);
                  do
                  {
                      while(scanf("%d", &seat) != 1)
                      {
                          scanf("%*s");
                          puts("Enter a number from the list: ");
                          puts(list);
                      }
                      if(seat < 1 || seat > SEATS || pl[seat - 1].status == TAKEN)
                      {
                          puts("Enter a number from the list: ");
                          puts(list);
                          loop = CONTINUE;
                      }
                      else
                          loop = DONE;

                  } while(loop);
                  while(getchar() != '\n')
                      continue;
                  puts("Enter the first name: ");
                  s_gets(pl[seat - 1].first, LEN);
                  puts("Enter the last name: ");
                  s_gets(pl[seat - 1].last, LEN);
                  printf("%s %s assigned to seat %d.\n", pl[seat - 1].first, pl[seat - 1].last, seat);
                  printf("Enter a to accept assignment, c to cancal it.\n");
                  if(getlet("ac") == 'a')
                  {
                      pl[seat - 1].status = TAKEN;
                      pl[seat - 1].seat_id = seat;  // 也得把座位編號給填上去吧!!!
                      puts("Passenger assigned to seat.");
                  }
                  else
                      puts("Passenger not assigned.");
              }

          }
          void delete_seat(struct planestats * pl, int n)
          {
              char list[3 * SEATS];
              int seat, loop;

              if(openings(pl, n) == SEATS)
                  puts("All seats already are empty.");
              else
              {
                  show_seat(pl, n);
                  makelist(pl, list, TAKEN);
                  puts("Enter the number of the seat to be cancelled: ");
                  puts(list);
                  do
                  {
                      while(scanf("%d", &seat) != 1)
                      {
                          scanf("%*s");
                          puts("Enter a number from the list: ");
                          puts(list);
                      }
                      if(seat < 1 || seat > SEATS || pl[seat - 1].status == EMPTY)
                      {
                          puts("Enter a number from the list: ");
                          puts(list);
                          loop = CONTINUE;
                      }
                      else
                          loop = DONE;
                  } while(loop);
                  while(getchar() != '\n')
                      continue;
                  printf("%s %s to be cancelled for seat.\n", pl[seat - 1].first, pl[seat - 1].last, seat);
                  puts("Enter d to delete assignment, a to abort.");
                  if(getlet("da") == 'd')
                  {
                      pl[seat - 1].status = EMPTY;
                      pl[seat - 1].seat_id = seat;  // 也得把座位編號給填上去吧!!!
                      puts("Passenger dropped.");
                  }
                  else
                      puts("Passenger retained.");
              }

          }
          void show_seat(const struct planestats * pl, int n)
          {
              for(int i = 0; i < n; i++)
                  if(pl[i].status == TAKEN)
                      printf("Seat %d: %s %s\n", pl[i].seat_id, pl[i].last, pl[i].first);
          }

          char * s_gets(char * s, int n)
          {
              char * ret_val;
              char * find;

              ret_val = fgets(s, n, stdin);
              if(ret_val)
              {
                  find = strchr(ret_val, '\n');
                  if(find)
                      *find = '\0';
                  else
                      while(getchar() != '\n')
                          continue;
              }
              return ret_val;
          }
          運行效果圖就不貼了,太大了!!!

          9、(沒有讀懂題意,不過借鑒30歲學編程http://xiongyi85.blog.51cto.com/8756903/1660546前輩,才搞明白,與編程練習8相似,不過它是處理一個航班,該程序處理的是多個航班!!!)
          #include <stdio.h>
          #include <string.h>
          #include <stdlib.h>
          #define LEN 14
          #define EMPTY 0
          #define TAKEN 1
          #define CONTINUE 1
          #define DONE 0
          #define SEATS 12
          #define AIRS 4
          #define CHOICES 6
          /* 每個planestats結構標識一個座位 */
          struct planestats {
              int seat_id;
              int status;
              char last[LEN];
              char first[LEN];
          };
          struct air {
              int air_id;
              struct planestats place[SEATS];  // 嵌套結構數組(第一次見)
          };
          int get_top_menu(void);
          int getmenu(void);
          void get_ret(struct planestats *, int);
          //void verse(struct air *, struct planestats *, int);
          int getlet(const char *);
          int openings(const struct planestats *, int);
          void show_empties(const struct planestats *, int);
          void makelist(const struct planestats *, char *, int);
          void list_assgin(struct planestats *[], int);
          void sort(struct planestats *[], int);
          void assign_seat(struct planestats *, int);
          void delete_seat(struct planestats *, int);
          void show_seat(const struct planestats *, int);
          char * s_gets(char *, int);

          int main(void)
          {
              struct air plane[AIRS];
              int choice;
              int i, j;
              FILE *fp;
              size_t size = sizeof(struct air);

              /* 若文件air.dat打不開,則初始化結構數組 */
              if((fp = fopen("air_1.dat", "rb")) == NULL)
              {
                  for(i = 0; i < AIRS; i++)
                  {
                      switch(i)
                      {
                          case 0: plane[i].air_id = 102;
                                  break;
                          case 1: plane[i].air_id = 311;
                                  break;
                          case 2: plane[i].air_id = 444;
                                  break;
                          case 3: plane[i].air_id = 519;
                                  break;
                      }
                      for(j = 0; j < SEATS; j++)
                      {
                          plane[i].place[j].status = EMPTY;
                          plane[i].place[j].seat_id = j + 1; // 編號從1開始
                      }
                  }
              }
              else
              {
                  fread(plane, size, AIRS, fp); // 一次寫入結構數組plane_1中
                  fclose(fp);
              }
              while((choice = get_top_menu()) != 'q')
              {
                  switch(choice)
                  {
                      case 'a': get_ret(plane[0].place, plane[0].air_id); // 其實參數只要傳前一個就可以,沒必要也把air_id也傳過去,因為沒用上
                                break;
                      case 'b': get_ret(plane[1].place, plane[1].air_id);
                                break;
                      case 'c': get_ret(plane[2].place, plane[2].air_id);
                                break;
                      case 'd': get_ret(plane[3].place, plane[3].air_id);
                                break;
                  }
              }
              if((fp = fopen("air_1.dat", "wb")) == NULL)
                  puts("Can't save data to file.");
              else
              {
                  fwrite(plane, size, AIRS, fp); // 將結構數組一次寫入到文件中
                  fclose(fp);
              }
              puts("Bye from Colossus Airlines!");
              return 0;
          }
          int get_top_menu(void)
          {
              const char * top_descript[AIRS + 1] = {
                  "102 6:00",
                  "311 7:45",
                  "444 13:00",
                  "519 15:45",
                  "Quit"
              };
              const char top_labels[AIRS + 2] = "abcdq";

              puts("Welcome to do giant aviation, you can choose the following flight: ");
              for(int i = 0; i < AIRS; i++)
                  printf("%c) %s\n", top_labels[i], top_descript[i]);
              return getlet(top_labels);
          }
          int getmenu(void)
          {
              const char * descript[CHOICES] = {
                  "Show number of empty seats",
                  "Show list of empty seats",
                  "Show alphabetical list of seats",
                  "Assign a customer to a seat assignment",
                  "Delete a seat assignment",
                  "Quit"
              };
              const char labels[CHOICES + 1] = "oeladq";
              int i;

              puts("To choose a function, enter its letter label: ");
              for(i = 0; i < CHOICES; i++)
                  printf("%c) %s\n", labels[i], descript[i]);
              return getlet(labels);
          }
          /*
          void verse(struct air * air_1, struct planestats * pl, int air_id)
          {
              for(int i = 0; i < SEATS; i++)
                  pl[i] = air_1[air_id].place[i];
          }
          */
          void get_ret(struct planestats * plane_1, int air_id)
          {
              int choice;
              struct planestats *ps[SEATS];
              /*switch(air_id)
              {
                  case 102: verse(air_1, plane_1, air_id);
                            break;
                  case 311: verse(air_1, plane_1, air_id);
                            break;
                  case 444: verse(air_1, plane_1, air_id);
                            break;
                  case 519: verse(air_1, plane_1, air_id);
                            break;
              }
          */
              for(int i = 0; i < SEATS; i++)
                  ps[i] = &plane_1[i];
              while((choice = getmenu()) != 'q')
              {
                  switch(choice)
                  {
                      case 'o': printf("There are %d empty seats.\n",
                                openings(plane_1, SEATS));
                                break;
                      case 'e': show_empties(plane_1, SEATS);
                                break;
                      case 'l': list_assgin(ps, SEATS);
                                break;
                      case 'a': assign_seat(plane_1, SEATS);
                                break;
                      case 'd': delete_seat(plane_1, SEATS);
                                break;
                  }
              }
          }
          int getlet(const char * s)
          {
              char c;

              c= getchar();
              while(strchr(s, c) == NULL)
              {
                  printf("Enter a character in the list %s\n", s);
                  while(getchar() != '\n')
                      continue;
                  c = getchar();
              }
              while(getchar() != '\n')
                  continue;
              return c;
          }
          int openings(const struct planestats * pl, int n)
          {
              int count = 0;
              int seat;

              for(seat = 0; seat < n; seat++)
                  if(pl[seat].status == EMPTY)
                      count++;
              return count;
          }
          void show_empties(const struct planestats * pl, int n)
          {
              char seating[3 * SEATS];

              if(openings(pl, n) == 0)
                  printf("All seats are assigned\n");
              else
              {
                  puts("The following seats are available: ");
                  makelist(pl, seating, EMPTY);
                  puts(seating);
              }
          }
          void makelist(const struct planestats * pl, char * str, int kind)
          {
              int seat;
              char temp[LEN];

              str[0] = '\0';
              for(seat = 0; seat < SEATS; seat++)
                  if(pl[seat].status == kind)
                  {
                      sprintf(temp, " %d", pl[seat].seat_id); // 把格式化輸出寫到指定的字符串中
                      strcat(str, temp);
                  }
          }
          void list_assgin(struct planestats *ps[], int n)
          {
              int i;

              if(openings(*ps, n) == n)
                  puts("All seats are empty.");
              else
              {
                  sort(ps, n);
                  for(i = 0; i < n; i ++)
                      if(ps[i]->status == TAKEN)
                          printf("Seat %d: %s, %s\n", ps[i]->seat_id, ps[i]->last, ps[i]->first);
              }
          }
          void sort(struct planestats *array[], int n)
          {
              int top, search;
              struct planestats * temp;

              for(top = 0; top < n - 1; top++)
                  for(search = top + 1; search < n; search++)
                  if(strcmp(array[top]->last, array[search]->last) > 0)
                  {
                      temp = array[top];
                      array[top] = array[search];
                      array[search] = temp;
                  }
          }
          void assign_seat(struct planestats * pl, int n)
          {
              char list[3 * SEATS];
              int seat, loop;

              if(openings(pl, n) == 0)
                  puts("All seats are assigned.");
              else
              {
                  makelist(pl, list, EMPTY);
                  puts("Which seat do you want? Choose from the list: ");
                  puts(list);
                  do
                  {
                      while(scanf("%d", &seat) != 1)
                      {
                          scanf("%*s");
                          puts("Enter a number from the list: ");
                          puts(list);
                      }
                      if(seat < 1 || seat > SEATS || pl[seat - 1].status == TAKEN)
                      {
                          puts("Enter a number from the list: ");
                          puts(list);
                          loop = CONTINUE;
                      }
                      else
                          loop = DONE;

                  } while(loop);
                  while(getchar() != '\n')
                      continue;
                  puts("Enter the first name: ");
                  s_gets(pl[seat - 1].first, LEN);
                  puts("Enter the last name: ");
                  s_gets(pl[seat - 1].last, LEN);
                  printf("%s %s assigned to seat %d.\n", pl[seat - 1].first, pl[seat - 1].last, seat);
                  printf("Enter a to accept assignment, c to cancal it.\n");
                  if(getlet("ac") == 'a')
                  {
                      pl[seat - 1].status = TAKEN;
                      pl[seat - 1].seat_id = seat;  // 也得把座位編號給填上去吧!!!
                      puts("Passenger assigned to seat.");
                  }
                  else
                      puts("Passenger not assigned.");
              }

          }
          void delete_seat(struct planestats * pl, int n)
          {
              char list[3 * SEATS];
              int seat, loop;

              if(openings(pl, n) == SEATS)
                  puts("All seats already are empty.");
              else
              {
                  show_seat(pl, n);
                  makelist(pl, list, TAKEN);
                  puts("Enter the number of the seat to be cancelled: ");
                  puts(list);
                  do
                  {
                      while(scanf("%d", &seat) != 1)
                      {
                          scanf("%*s");
                          puts("Enter a number from the list: ");
                          puts(list);
                      }
                      if(seat < 1 || seat > SEATS || pl[seat - 1].status == EMPTY)
                      {
                          puts("Enter a number from the list: ");
                          puts(list);
                          loop = CONTINUE;
                      }
                      else
                          loop = DONE;
                  } while(loop);
                  while(getchar() != '\n')
                      continue;
                  printf("%s %s to be cancelled for seat.\n", pl[seat - 1].first, pl[seat - 1].last, seat);
                  puts("Enter d to delete assignment, a to abort.");
                  if(getlet("da") == 'd')
                  {
                      pl[seat - 1].status = EMPTY;
                      pl[seat - 1].seat_id = seat;  // 也得把座位編號給填上去吧!!!
                      puts("Passenger dropped.");
                  }
                  else
                      puts("Passenger retained.");
              }

          }
          void show_seat(const struct planestats * pl, int n)
          {
              for(int i = 0; i < n; i++)
                  if(pl[i].status == TAKEN)
                      printf("Seat %d: %s %s\n", pl[i].seat_id, pl[i].last, pl[i].first);
          }

          char * s_gets(char * s, int n)
          {
              char * ret_val;
              char * find;

              ret_val = fgets(s, n, stdin);
              if(ret_val)
              {
                  find = strchr(ret_val, '\n');
                  if(find)
                      *find = '\0';
                  else
                      while(getchar() != '\n')
                          continue;
              }
              return ret_val;
          }

          10、(借鑒http://ptgmedia.pearsoncmg.com/images/9780321928429/downloads/9780321928429_ProgrammingExerciseAnswers_Selected.pdf的做法)
          #include <stdio.h>
          #include <math.h>
          #define NUM 4
          double twice(double x);
          double half(double x);
          double thrice(double x);
          void showmenu(void);

          int main(void)
          {
              double (*fp[NUM])(double) = {twice, half, thrice, sqrt};
              double val, ans;
              int choice;

              puts("Enter a number (negative to quit): ");
              while(scanf("%lf", &val) == 1 && val > 0)
              {
                  showmenu();
                  while(scanf("%d", &choice) == 1 && choice >= 0 && choice <= 3)
                  {
                      ans = (*fp[choice])(val); // ans = fp[choice](val);
                      printf("answer = %.2f\n", ans);
                      showmenu();
                  }
                  puts("Enter a number (negative to quit): ");
              }
              puts("Bye.");
              return 0;
          }
          void showmenu(void)
          {
              puts("Enter one of the following choices: ");
              puts("0) double the value            1) halve the value");
              puts("2) triple the value            3) squareroot the value");
              puts("4) next number");
          }
          double twice(double x)
          {
              return 2.0 * x;
          }
          double half(double x)
          {
              return x / 2.0;
          }
          double thrice(double x)
          {
              return 3.0 * x;
          }

          11、
          #include <stdio.h>
          #include <math.h>
          #define NUM 100

          double twice(double x);
          double thrice(double x);
          void transform(double * sou, double * tar, int n, double (*fp)(double));
          void show(const double *, int);
          int main(void)
          {
              double source[NUM];
              double target0[NUM];
              double target1[NUM];
              double target2[NUM];
              double target3[NUM];

              for(int i = 0; i < NUM; i++)
                  source[i] = i + 1;
              transform(source, target0, NUM, twice);
              transform(source, target1, NUM, thrice);
              transform(source, target2, NUM, sqrt);
              transform(source, target3, NUM, sin);
              puts("--------------------------target0數組--------------------------");
              show(target0, NUM);
              puts("--------------------------target1數組--------------------------");
              show(target1, NUM);
              puts("--------------------------target2數組--------------------------");
              show(target2, NUM);
              puts("--------------------------target3數組--------------------------");
              show(target3, NUM);
              return 0;
          }
          double twice(double x)
          {
              return 2.0 * x;
          }
          double thrice(double x)
          {
              return 3.0 * x;
          }
          void transform(double * sou, double * tar, int n, double (*fp)(double))
          {
              for(int i = 0; i < n; i++)
                  tar[i] = (*fp)(sou[i]);
          }
          void show(const double * arr, int n)
          {
              int i;

              for(i = 0; i < n; i++)
              {
                  printf("%7.2f", arr[i]);
                  if(i % 10 == 9)
                      putchar('\n');
              }
              if(i % 10 != 9)
                  putchar('\n');
          }
          總結:這一章是尤其難的,基本上每一題都比較難搞定,不過還是勉強做完!!!
          posted on 2015-12-10 16:53 李阿昀 閱讀(1574) 評論(0)  編輯  收藏 所屬分類: C Primer Plus 復習題與編程練習
          主站蜘蛛池模板: 五常市| 弥渡县| 宁武县| 洛宁县| 翁牛特旗| 平舆县| 明光市| 板桥市| 洪雅县| 黑河市| 高要市| 玉屏| 隆安县| 葫芦岛市| 从化市| 湘乡市| 大竹县| 惠水县| 离岛区| 景泰县| 黔东| 长寿区| 瓮安县| 清河县| 三都| 甘孜县| 海阳市| 龙泉市| 佛坪县| 山东省| 桦川县| 珠海市| 平陆县| 工布江达县| 大石桥市| 昆明市| 临洮县| 宁蒗| 司法| 宁津县| 井研县|