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 李阿昀 阅读(1540) 评论(0)  编辑  收藏 所属分类: C Primer Plus 复习题与编程练习

只有注册用户登录后才能发表评论。


网站导航: