C primer plus第14章(结构和其他数据形式)(练习)

//练习3、4、5
#include <stdio.h>

struct month
{
    char name[10];
    char nik[4];
    int days;
    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}
};

int getDays(int month)
{
    int i;
    int totaldays = 0;
    extern struct month months[];
    for(i=1; i<month; i++)
    {
        totaldays += months[i].days;
    }
    return totaldays;
}


int main(void)
{
    printf("%d",getDays(2));
    return 0;
}

//练习6
#include <stdio.h>
#include <string.h>
typedef struct lens  //镜头描述
{
    float foclen;   //焦距长度,以mm为单位
    float fstop;    //孔径
    char brand[30]; //品牌名称
} LENS;


int main(void)
{
    //a赋值
    LENS l[10];
    l[2].foclen = 500;
    l[2].fstop = 2.0;
    //字符串如不赋值拷贝的只是地址
    strcpy(l[2].brand,"Remarkatar");
    //b直接初始化第三个下标的元素
    LENS bigEye[10] = {[2] = {500,2,"Remarkatar"}};
    return 0;
}

练习7

#include <stdio.h>
struct name
{
    char first[20];
    char last[20];
};
struct bem
{
    int limbs;
    struct name title;
    char type[30];
};

int main(void)
{
    struct bem *pb;
    struct bem deb =
    {
        6,
        {"Berbanazel","Gwolkapwolk"},
        "Arcturan"
    };
    pb = &deb;

    printf("%d\n",deb.limbs);
    printf("%s\n",pb->type);
    printf("%s\n",pb->type+2);
    return 0;
}
打印结果
6
Arcturan
cturan


b使用结构鸣并使用指针

deb.title.last

pb->title.last

c

void show(const struct bem *pb)
{
    printf("%s %s is a %d-limbed %s.",pb->title.first,pb->title.last,pb->limbs,pb->type);

}


8


#include <stdio.h>
struct fullname
{
    char fname[20];
    char lname[20];
};
struct bard
{
    struct fullname name;
    int born;
    int died;
};


int main(void)
{
    struct bard willie;
    struct bard *pt = &willie;
    //a
    willie.born;
    //b
    pt->born;
    //c
    scanf("%d",willie.born);
    //d
    scanf("%d",pt->born);
    //e
    scanf("%d",willie.name.lname);
    //f
    scanf("%d",pt->name.lname);
    //g
    willie.name.fname[2];
    //h
    strlen(willie.name.fname) + strlen(willie.name.lname);
    return 0;
}




9
struct car
{
    char name[100];//车名
    int horseprower;//马力
    int epa;//epa英里每加仑(mpg)等级
    float wheelBase; //轴距
    int years;//使用年限
};

10

struct gas
{
    float distance;
    float gals;
    float mpg;
};
//a
struct gas cal(struct gas g)
{
    g.mpg = g.distance * g.gals;
    return g;
}
//b
void cal2(struct gas * g)
{
    g->mpg = g->distance * g->gals;
}

11

enum choices{
    no,
    yes,
    maybe
};

12 

char *(*pfun)(char *,char)

char *    返回值是个char指针

(*pfun) 是函数指针

(char *,char) 2个参数一个char指针,一个char

13

double a(double, double);
double b(double, double);
double c(double, double);
double d(double, double);


double (*abcd[4])(double,double) = {a,b,c,d};
//或者
typedef double (*abcd)(double,double);
abcd d[4] = {a,b,c,d};


编程练习

1.

//练习3、4、5
#include <stdio.h>

struct month
{
    char name[10];
    char nik[4];
    int days;
    int month;
};
//枚举类型代替1-12的数字
enum monthEnum
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
};
//月份用枚举标示
struct month months[12] =
{
    {"January","jan",31,January},
    {"February","feb",28,February},
    {"March","mar",31,March},
    {"April","apr",30,April},
    {"May","may",31,May},
    {"June","jun",30,June},
    {"July","jul",31,July},
    {"August","aug",31,August},
    {"September","sep",30,September},
    {"October","oct",31,October},
    {"November","nov",30,November},
    {"December","dec",31,December}
};

int getDays(int month)
{
    int i;
    int totaldays = 0;
    extern struct month months[];
    for(i=1; i<month; i++)
    {
        totaldays += months[i].days;
    }
    return totaldays;
}


int main(void)
{
    printf("%d",getDays(2));
    return 0;
}

2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct month
{
    char name[10];
    char nik[4];
    int days;
    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}
};
int getDays(int year, const struct month *m,int day);

int main(void)
{
    size_t year,day,i;
    char mon[20];
    struct month *m = NULL;
    printf("请输入年份:");
    while(scanf("%d",&year) != 1)
    {
        printf("请输入一个正整数年份:");
    }
    //吃掉回城符
    getchar();
    printf("请输入月份:");
    gets(mon);
    while(m == NULL)
    {
        for(i=1; i<= 12; i++)
        {
            if(strcmp(months[i].name,mon) == 0 || strcmp(months[i].nik,mon) == 0 || months[i].month == atoi(mon))
            {
                m = &months[i];
            }
        }
    }
    printf("请输入日期:");
    while(scanf("%d",&day) != 1)
    {
        printf("请输入一个正整数日期:");
    }
    printf("%d",getDays(year,m,day));
    return 0;
}

//根据年月日获取天数
int getDays(int year, const struct month *m,int day)
{
    if(year< 0 || day <0 || day > m->days)
    {
        printf("year = %d, day=%d,m->day = %d",year,day,m->days);
        return 0;
    }

    int totaldays = 0;
    if(m->month == 2 && year%4 == 0 && year%100 !=0)
    {
        totaldays++;
    }
    int i;
    for(i=0; i<m->month-1; i++)
    {
        totaldays += months[i].days;
    }
    totaldays += day;
    return totaldays;
}

3

#include <stdio.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 100 //图书最多的本书

//建立book模板
struct book
{
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};
void titleSort(struct book library[],int count);
void valueSort(struct book library[],int count);
int main(void)
{
    struct book library[MAXBKS];//结构数组
    int count = 0;
    int index;
    //如果文件还能存储
    puts("Please enter the book title.");
    puts("Press [enter] at the start of a line to stop.");
    //录入新的图书
    while(count <MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0')
    {
        puts("Now enter the author.");
        gets(library[count].author);
        puts("Now enter the value.");
        //下标递增
        scanf("%f",&library[count++].value);
        //清空输入行
        while(getchar() != '\n')
        {
            continue;
        }
        //如果未大于最大存储数量,提示输入下一本
        if(count< MAXBKS)
        {
            puts("Enter the next title");
        }
    }
    if(count > 0)
    {
        puts("Here is the list of your books:");
        for(index = 0; index < count; index++)
        {
            printf("%s by %s:$%.2f\n",library[index].title,library[index].author,library[index].value);
        }
        titleSort(library,count);
        valueSort(library,count);
    }
    else
    {
        puts("No books? Too bad.\n");
    }
    return 0;
}


void titleSort(struct book library[],int count)
{
    printf("\n按title首字母升序:\n");
    int i,j,temp,flag;
    int sort[count];
    for(i=0; i<count; i++)
    {
        sort[i] = i;
    }
    //选择排序
    for(i=0; i<count-1; i++)
    {
        temp = sort[i];
        flag = i;
        for(j=i+1; j<count; j++)
        {
            if(library[temp].title[0] > library[sort[j]].title[0])
            {
                temp = sort[j];
                flag = j;
            }
            if(flag != i)
            {
                sort[flag] = sort[i];
                sort[i] = temp;
            }
        }
    }
    for(i=0; i<count; i++)
    {
        printf("%s by %s:$%.2f\n",library[sort[i]].title,library[sort[i]].author,library[sort[i]].value);
    }
}


void valueSort(struct book library[],int count)
{
    printf("\n按value升序:\n");

    int i,j,temp,flag;
    int sort[count];
    for(i=0; i<count; i++)
    {
        sort[i] = i;
    }
    //选择排序
    for(i=0; i<count-1; i++)
    {
        flag = i;
        for(j=i+1; j<count; j++)
        {
            if(library[sort[flag]].value>library[sort[j]].value)
            {
                flag = j;
            }
            if(flag != i)
            {
                temp = sort[i];
                sort[i] = sort[j];
                sort[j] = temp;
            }
        }
    }
    for(i=0; i<count; i++)
    {
        printf("%s by %s:$%.2f\n",library[sort[i]].title,library[sort[i]].author,library[sort[i]].value);
    }
}

4

#include <stdio.h>
#include <string.h>
//建立book模板
struct name
{
    char firstName[20];
    char middleName[20];
    char lastName[20];
};
struct citizen
{
    int socialSecurityNO;
    struct name citizenName;
};
void printA(const struct citizen country);
void printB(const struct citizen *country);

int main(void)
{
    int i;
    struct citizen country[5] =
    {
        {10000001,{"h1","x1","l"}},
        {10000002,{"h2","","l"}},
        {10000003,{"h3","x3","l"}},
        {10000004,{"h4","x4","l"}},
        {10000005,{"h5","x5","l"}}
    };
    for(i=0; i<5; i++)
    {
        //printA(country[i]);
        printB(&country[i]);
    }
    return 0;
}

void printA(const struct citizen country)
{
    printf("%s.%s ",country.citizenName.firstName,country.citizenName.lastName);
    if(strlen(country.citizenName.middleName) > 0)
    {
        printf("%c.",country.citizenName.middleName[0]);

    }
    printf("-%d\n",country.socialSecurityNO);
}

void printB(const struct citizen *country)
{
    printf("%s.%s ",country->citizenName.firstName,country->citizenName.lastName);
    if(strlen(country->citizenName.middleName) > 0)
    {
        printf("%c.",country->citizenName.middleName[0]);

    }
    printf("-%d\n",country->socialSecurityNO);
}

5

#include <stdio.h>
#define CSIZE 4
//建立book模板
struct name
{
    char firstName[20];
    char lastName[20];
};
struct student
{
    struct name sname;
    //分数
    float grade[3];
    //平均分
    double avgGrade;
};

void getStudent(struct student *s);
void putStudents(struct student students[]);
int main(void)
{
    struct student students[CSIZE];
    int i;
    for(i=0; i<CSIZE; i++)
    {
        printf("第%d名学生\n",i+1);
        getStudent(&students[i]);
    }
    putStudents(students);
    return 0;
}

void getStudent(struct student *s)
{
    puts("请输入姓");
    gets(s->sname.firstName);
    puts("请输入名");
    gets(s->sname.lastName);
    int i;
    double total = 0;
    for(i=0; i<3; i++)
    {

        printf("请输第%d门分数",i+1);
        scanf("%f",&s->grade[i]);
        getchar();
        total += s->grade[i];
    }
    s->avgGrade = total/3;
}

void putStudents(struct student students[])
{
    int i,j;
    double total = 0;
    for(i =0; i<CSIZE; i++)
    {
        printf("学生%s.%s\n",students[i].sname.firstName,students[i].sname.lastName);
        for(j=0; j<3; j++)
        {
            printf("成绩%d:%f\n",j+1,students[i].grade[j]);
        }
        total += students[i].avgGrade;
    }
    printf("班级平均成绩%lf",total/CSIZE);

}

6(未完成)

//练习3、4、5
#include <stdio.h>
#include <stdlib.h>
#define LEN 20
#define MAX 100
//棒球选手
typedef struct ballplayer
{
    //球员编号
    size_t no;
    char lastname[LEN];
    char firstname[LEN];
    //上场击球次数
    int timesAtBat;
    //击中数
    int timesAtHit;
    //跑垒数
    int timesAtBaseRunning;
    //跑点数
    int RBI;
    //平均成功率
    double averageSuccessRatio;
} BP;

int getInt();
void getBallPalyer(BP *bp);

int main(void)
{
    BP team[MAX];
    int size = sizeof(BP);
    FILE *fp;
    int index = 0;
    if((fp = fopen("team.txt","r")) == NULL)
    {
        puts("文件打开失败");
        exit(EXIT_FAILURE);
    }
    while(fread(&team[index++],size,1,fp) == 1)
    {
        printf("%d %s.%s %d %d %d %d %d",team[index].no,team[index].firstname,team[index].lastname,team[index].timesAtBat,team[index].timesAtHit,team[index].timesAtBaseRunning,team[index].RBI,team[index].averageSuccessRatio);
    }


    return 0;
}


void getBallPalyer(BP *bp)
{
    puts("请录入球员编号!");
    bp->no = getInt();
    puts("请输入球员姓:");
    gets(bp->firstname);
    puts("请输入球员名:");
    gets(bp->lastname);
    puts("请输入上场击球次数");
    //上场击球次数
    bp->timesAtBat = getInt();
    //击中数
    bp->timesAtHit = getInt();
    //跑垒数
    bp->timesAtBaseRunning = getInt();
    //跑点数
    bp->RBI = getInt();
    //平均成功率
    bp->averageSuccessRatio = bp->timesAtHit / bp->timesAtBat;

}

//获取int型的输入参数
int getInt()
{
    int num;
    while(scanf("%d",&num) != 1)
    {
        while(getchar() != '\n')
        {
            continue;
        }
        puts("请输入数字类型的编号");
    }
    return num;
}








7

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10 //图书最多的本书
#define CONTINUE 0
#define DONE 1
#define YES 1
#define NO 0
//建立book模板
struct book
{
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
    //记录删除状态
    int del;
};

int getlet(const char *s);
int getbook(struct book *pb);
void update(struct book * item);

int main(void)
{
    struct book 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].title,library[count].author,library[count].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 entry:");
                //获取输入
                if(getlet("cd") == 'd')
                {
                    //删除标记
                    library[count].del = YES;
                    //删除数量增加
                    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(2);
    }

    //如果文件还能存储
    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].del == NO)
            {
                //此变量唯一用途是为后面新增书查询下标
                open++;
            }
            //录入新的图书
            if(getbook(&library[open]) == DONE)
            {
                break;
            }
        }
        else if(getbook(&library[filecount]) == DONE)
        {
            //如果没有删除的书
            break;
        }
        //继续统计新增后的书总量(扣除删除的)
        filecount++;
        if(filecount < MAXBKS)
        {
            puts("Enter the next book title.");
        }
    }
    puts("Here is the list of your books:");
    for(index = 0; index<filecount; index++)
    {
        if(library[index].del == NO)
        {
            printf("%s by %s: $%.2f\n",library[index].title,library[index].author,library[index].value);
        }
    }
    //以写入(清空文件内容)的方式打开文件流
    if((pbooks = fopen("book.dat","w")) == NULL)
    {
        fputs("Can`t open book.dat file for output\n",stderr);
        exit(1);
    }
    //写入文件
    for(index = 0; index<filecount; index++)
    {
        //删除的数据不写入
        if(library[index].del == NO)
        {
            fwrite(&library[index],size,1,pbooks);
        }
    }
    //关闭文件流
    fclose(pbooks);
    puts("Done!");
    return 0;
}
//参数传入一个字符串,获取输入,字符串中的一个字符
int getlet(const char * s)
{
    char c;
    c = getchar();

    //功能:查找字符串s中首次出现字符c的位置
    //说明:返回首次出现c的位置的指针,如果s中不存在c则返回NULL。
    while(strchr(s,c) == NULL)
    {
        printf("Enter a character in the list %s\n",s);
        //清空输入行 比如scanf()没有对'\n'做处理
        while(getchar() != '\n')
        {
            continue;
        }
        //继续获取输入
        c=getchar();
    }
    while(getchar() != '\n')
    {
        continue;
    }
    return c;
}

//录入新书
int getbook(struct book * pb)
{
    int status = CONTINUE;

    if(gets(pb->title) == NULL || pb->title[0] == '\0')
    {
        status = DONE;//退出输出
    }
    else
    {
        printf("Now enter the auther:");
        gets(pb->author);
        printf("Now enter the value:");
        while(scanf("%f",&pb->value) != 1)
        {
            puts("Please use numeric input");
            scanf("%*s");
        }
        while(getchar() != '\n')
        {
            continue;//clear input line
        }
        pb->del = NO;

    }
    return status;
}

void update(struct book * item)
{
    struct book copy;
    char c;
    copy = *item;
    //修改菜单
    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:");
            gets(copy.title);
            break;
        case 'a':
            puts("Enter new author:");
            gets(copy.author);
        case 'v':
            puts("Enter new value:");
            while(scanf("%f",©.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 = copy;
    }
}

8(丑陋,但是完成了)

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>//bool头文件
#include <string.h>
#define LEN 12

//座位席模板
typedef struct planeSeat
{
    //座位号
    char no;
    //是否已预订
    bool booked;
    char firstName[LEN];
    char lastName[LEN];
} PSEAT;

int getlet(const char *s);
//读取文件
void readFile(PSEAT *p,int size);
//写入文件
void writeFile(PSEAT *p,int size);
//显示剩余座位数
void showNumberOfEmptySeats(PSEAT *p);
//显示剩余座位列表
void showListOfEmptySeats(PSEAT *p);
//按字母显示预订座位列表
void showAlphabeticalListOfSeats(PSEAT *p);
//预订座位
void AssignACustomer(PSEAT *p);
//删除预订
void deleteACustomer(PSEAT *p);
//显示菜单
void menu(PSEAT *p);

int main(void)
{
    int size = sizeof(PSEAT);
    PSEAT p[LEN];
    readFile(p,size);
    menu(p);
    writeFile(p,size);
    return 0;
}
void writeFile(PSEAT *p,int size)
{
    int i;
    FILE *fp = fopen("seatBook.dat","w");
    for(i=0; i<LEN; i++)
    {
        fwrite((p+i),size,1,fp);
    }
}

void readFile(PSEAT *p,int size)
{
    FILE *fp;
    int i;

    if((fp = fopen("seatBook.dat","r")) != NULL)
    {
        for(i=0; i<LEN; i++)
        {
            fread((p+i),size,1,fp);
        }
        fclose(fp);
    }
    else
    {
        for(i=0; i<LEN; i++)
        {

            (p+i)->no = i;
            (p+i)->booked = false;

        }
    }
}


//参数传入一个字符串,获取输入,字符串中的一个字符
int getlet(const char * s)
{
    char c;
    c = getchar();

    //功能:查找字符串s中首次出现字符c的位置
    //说明:返回首次出现c的位置的指针,如果s中不存在c则返回NULL。
    while(strchr(s,c) == NULL)
    {
        printf("Enter a character in the list %s\n",s);
        //清空输入行 比如scanf()没有对'\n'做处理
        while(getchar() != '\n')
        {
            continue;
        }
        //继续获取输入
        c=getchar();
    }
    while(getchar() != '\n')
    {
        continue;
    }
    return c;
}

void showNumberOfEmptySeats(PSEAT *p)
{
    int count = 0;
    int i;
    for(i=0; i<LEN; i++)
    {
        if((p+i)->booked == false)
        {
            count++;

        }
    }
    printf("\n%d SEATS ARE not booked\n",count);
}


void showListOfEmptySeats(PSEAT *p)
{
    int i;
    for(i=0; i<LEN; i++)
    {
        if((p+i)->booked == false)
        {
            printf("NO.%d SEAT not booked\n",(p+i)->no);
        }
    }
}

void showAlphabeticalListOfSeats(PSEAT *p)
{
    int sorts[LEN];
    int i,j,flag,temp;
    for(i=0; i<LEN; i++)
    {
        sorts[i] = i;
    }
    for(i = 0; i< LEN-1; i++)
    {
        flag = i;
        for(j = i+1; j <LEN ; j++)
        {
            if((p+sorts[i])->firstName[0] > (p+sorts[j])->firstName[0])
            {
                flag = j;
            }
        }
        if(flag != i)
        {

            temp = sorts[flag];
            sorts[flag] = sorts[i];
            sorts[i] = temp;
        }
    }

    for(i=0; i<LEN; i++)
    {
        if((p+sorts[i])->booked == true)
        {
            printf("NO.%d SEAT is booked by %s.%s\n",(p+sorts[i])->no,(p+sorts[i])->firstName,(p+sorts[i])->lastName);
        }
    }

}

//预订座位
void AssignACustomer(PSEAT *p)
{
    int index;
    puts("请输入要预订的座位号");
    while(scanf("%d",&index) !=1 || index <0 || index > LEN)
    {
        while(getchar()!='\n')
        {
            continue;
        }
        puts("请输入0-12的数字");
    }
    while(getchar()!='\n')
    {
        continue;
    }
    puts("请输入姓");
    gets((p+index)->firstName);
    puts("请输入名字");
    gets((p+index)->lastName);
    (p+index)->booked = true;
}

void deleteACustomer(PSEAT *p)
{
    int index;
    puts("请输入要预订的座位号");
    while(scanf("%d",&index) !=1 || index <0 || index > LEN)
    {
        while(getchar()!='\n')
        {
            continue;
        }
        puts("请输入0-12的数字");
    }
    while(getchar()!='\n')
    {
        continue;
    }
    //p[index]->firstName = "";
    //p[index]->lastName = "";
    (p+index-1)->booked = false;
}

void menu(PSEAT *p)
{
    char ch;
    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 seat");
    puts("d)Assign a customer to a seat assignment");
    puts("e)Delete a seat assignment");
    puts("f)Quit");
    while((ch = getlet("abcdef")) != 'f')
    {
        switch(ch)
        {
        case 'a':
            showNumberOfEmptySeats(p);
            break;
        case 'b':
            showListOfEmptySeats(p);
            break;
        case 'c':
            showAlphabeticalListOfSeats(p);
            break;
        case 'd':
            AssignACustomer(p);
            break;
        case 'e':
            deleteACustomer(p);
            break;
        }
    }
}


8答案做法

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>//bool头文件
#include <string.h>
#define LEN 14
#define SEATS 12
#define EMPTY 0
#define TAKEN 1
#define CONTINUE 1
#define DONE 0
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 list_assign(struct planestats *[],int);
void assign_seat(struct planestats [],int);
void delete_seat(struct planestats [],int);
void show_seat(const struct planestats [],int);
void sort(struct planestats *[],int);
void makelist(const struct planestats [],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];
    }
    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;
        }
    }
    else
    {
        fread(plane_1,size,SEATS,fp);
        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_assign(ps,SEATS);
            break;
        case 'a':
            assign_seat(plane_1,SEATS);
            break;
        case 'd':
            delete_seat(plane_1,SEATS);
            break;
        default:
            puts("Switch trouble");
            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;
}

#define CHOICES 6
int getmenu(void)
{
    const char *descript[CHOICES] =
    {
        "Show number of empty seats",
        "Show list of empty seats",
        "Show alphabetical list of seat assignments",
        "Assign acustomer to a seat",
        "Delete a seat assignment",
        "Quit"
    };
    const char labels[CHOICES + 1] = "oeladq";
    int i;
    puts("To choose a function,enter its letter");
    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();

    //功能:查找字符串s中首次出现字符c的位置
    //说明:返回首次出现c的位置的指针,如果s中不存在c则返回NULL。
    while(strchr(s,c) == NULL)
    {
        printf("Enter a character in the list %s\n",s);
        //清空输入行 比如scanf()没有对'\n'做处理
        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)
{
    //int seat;
    char seating[3*SEATS];
    if(openings(pl,n) == 0)
    {
        puts("All seats are assigned");
    }
    else
    {
        puts("The following seats are avaliable:");
        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_assign(struct planestats *ps[],int n)
{
    int i;
    if(openings(*ps,n)==SEATS)
    {
        puts("All seats are empty.");
    }
    else
    {
        sort(ps,n);
        for(i =0; i<SEATS; i++)
        {
            if(ps[i]->status == TAKEN)
            {
                printf("Seat %d: %s. %s\n",ps[i]->seat_id,ps[i]->last,ps[i]->first);
            }
        }
    }
}

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 this list:");
        puts(list);
        do
        {
            while(scanf("%d",&seat) != 1)
            {
                scanf("%*s");
                puts("Enter a number from this list:");
                puts(list);
            }
            if(seat < 1 || seat > SEATS || pl[seat-1].status == TAKEN)
            {
                puts("Enter a number from this list:");
                puts(list);
                loop = CONTINUE;
            }
        }
        while(loop == CONTINUE);
        while(getchar() != '\n')
        {
            continue;
        }
        puts("Enter first name:");
        gets(pl[seat -1].first);
        puts("Enter last name:");
        gets(pl[seat -1].last);
        printf("%s %s assigned to seat %d.\n",pl[seat -1].first,pl[seat -1].last,seat);
        puts("Enter a to accpt assignment, c to cancel it.");
        if(getlet("ac") == 'a')
        {
            pl[seat - 1].status = TAKEN;
            puts("Passenger assigned to seat.");
        }
        else
        {
            puts("Passenger not assigned.");
        }
    }
}
void show_seats(const struct planestats pl[],int n)
{
    int i;
    puts("Seats currently taken:");
    for(i=0; i<SEATS; i++)
    {
        if(pl[i].status == TAKEN)
        {
            printf("Seat %d: %s, %s\n",pl[i].seat_id,pl[i].last,pl[i].first);
        }
    }
}

void delete_seat(struct planestats pl[],int n)
{
    int seat,loop;
    char list[3*SEATS];
    if(openings(pl,n) == SEATS)
    {
        puts("All seats already are empty.");
    }
    else
    {
        show_seats(pl,n);
        makelist(pl,list,TAKEN);
        puts("Enter the number of the seat to be cancelled:");
        do
        {
            while(scanf("%d",&seat) != 1)
            {
                scanf("%*s");
                puts("Enter a number from this list:");
                puts(list);
            }
            if(seat < 1 || seat > SEATS || pl[seat-1].status == EMPTY)
            {
                puts("Enter a number from this list;");
                puts(list);
                loop = CONTINUE;
            }
            else
            {
                loop = DONE;
            }
        }
        while(loop == CONTINUE);
        while(getchar() != '\n')
        {
            continue;
        }
        printf("%s %s to be canceled for seat %d.\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;
            puts("Passenger dropped.");
        }
        else
        {
            puts("Passenger retained.");
        }
    }
}



void sort(struct planestats *array[],int limit)
{
    int top,search;
    struct planestats * temp;
    for(top = 0; top<limit-1; top++)
    {
        for(search = top +1; search <limit; search++)
        {
            if(strcmp(array[search]->last,array[top]->last)<0)
            {
                temp = array[search];
                array[search] = array[top];
                array[top] = temp;
            }
        }
    }
}


10

#include <stdio.h>
#include <stdlib.h>
void MyFunA(int x);
void MyFunB(int x);
void MyFunC(int x);
void (*FunP)(int);
typedef void(*FunType)(int);//定义一个函数指针类型的FunTYPE
void CallMyFun(FunType fp,int x);
int main(void)
{
    size_t c;
    while((c = getchar()) != 'q')
    {
        switch(c)
        {
        case 'a':
            CallMyFun(MyFunA,2);
            break;
        case 'b':
            CallMyFun(MyFunB,2);
            break;
        case 'c':
            CallMyFun(MyFunC,2);
            break;
        }
    }
    return 0;
}

void CallMyFun(FunType fp,int x)
{
    fp(x);
}

void MyFunA(int x)
{
    printf("%d\n",10+x);
}

void MyFunB(int x)
{
    printf("%d\n",10-x);
}

void MyFunC(int x)
{
    printf("%d\n",10*x);
}

11

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 5
typedef double(*MyFun)(double);
void transform(double source[],double target[],int len,MyFun);
double add1(double x);
double reduce1(double x);
int main(void)
{
    double source[LEN] = {1.1,1.2,1.3,1.4,1.5};
    double target[LEN];
    //sin正弦
    transform(source,target,LEN,sin);
    //cos余弦
    transform(source,target,LEN,cos);
    transform(source,target,LEN,add1);
    transform(source,target,LEN,reduce1);
    return 0;
}

void transform(double source[],double target[],int len,MyFun s)
{
    int i;
    for(i=0; i<len; i++)
    {
        target[i] = s(source[i]);
        printf("%lf",target[i]);
    }
}

double add1(double x) {
    return x+1;
}

double reduce1(double x) {
    return x-1;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值