C Primer Plus第六版 第十四章编程练习

1.

#include 
#include 
#include 
#include 
#define LEN 4

struct month{
    char name[LEN];
    int days;
    int monumb;
};

struct month months[12] = {
    {"Jan", 31, 1},
    {"Feb", 28, 2},
    {"Mar", 31, 3},
    {"Apr", 30, 4},
    {"May", 31, 5},
    {"Jun", 30, 6},
    {"Jul", 31, 7},
    {"Aug", 31, 8},
    {"Sep", 30, 9},
    {"Oct", 31, 10},
    {"Nov", 30, 11},
    {"Dec", 31, 12},
};

int main(void)
{
    char monthname[LEN];
    int total = 0;
    int i;
    _Bool whether;

    printf("Enter the name of the month (first three letters) : ");
    fgets(monthname, LEN, stdin);

    for(i = 0; i < LEN; i++)
    {
        if(0 == i)
            monthname[i] = toupper(monthname[i]);
        else
            monthname[i] = tolower(monthname[i]);
    }
    for(i = 0; i < 12; i++)
    {
        total += months[i].days;  //进来先加一遍,月份是不是对另说
        if(strcmp(monthname, months[i].name) == 0)
        {
            whether = true;
            break;
        }
    }
    if(whether)
        printf("The total days of these months before your month are %d days.\n",total);
    else
        printf("Your input is undefined.\n");

    return 0;
}

 

2.

#include 
#include 
#include 
#include 
#define LEN 4

struct month{
    char name[LEN];
    int days;
    int monumb;
};

struct month months[12] = {
    {"Jan", 31, 1},
    {"Feb", 28, 2},
    {"Mar", 31, 3},
    {"Apr", 30, 4},
    {"May", 31, 5},
    {"Jun", 30, 6},
    {"Jul", 31, 7},
    {"Aug", 31, 8},
    {"Sep", 30, 9},
    {"Oct", 31, 10},
    {"Nov", 30, 11},
    {"Dec", 31, 12},
};

int main(void)
{
    char monthname[LEN];
    int total = 0;
    int year;
    int monthnum;
    int date;
    int ThisMonth;
    int i;
    _Bool whether;

    printf("Enter the year : ");  //读取用户输入的年份,并判断是否闰年
    scanf("%d", &year);
    if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)  //判断闰年,并改变二月份的天数
        months[1].days = 29;

    printf("Enter the name of the month (first three letters) or the number of the month : "); //读取用户输入的月份数,先计算到这个月月末的天数总和
    if(scanf("%d", &monthnum) == 1)
    {
        for(i = 0; i < monthnum; i++)
        {
            total += months[i].days;
            ThisMonth = months[i].days;
        }
    }   //先判断是不是数字,如果是就读取,因为整型不能接受字符串,而字符串可以接受单个输入数字
    else if(scanf("%s", monthname) == 1)
    {
        for(i = 0; i < LEN; i++)
        {
            if(0 == i)
                monthname[i] = toupper(monthname[i]);
            else
                monthname[i] = tolower(monthname[i]);
        }
        for(i = 0; i < 12; i++)
        {
            total += months[i].days;  //进来先加一遍,月份是不是对另说
            if(strcmp(monthname, months[i].name) == 0)
            {
                whether = true;
                ThisMonth = months[i].days;
                i = i + 1;
                break;
            }
        }
        if(!whether)
        {
            printf("Your input month is undefined.\n");
            return 1;
        }
    }

    printf("Enter the date : ");  //读取用户输入的日期,进行最后的计算
    if(scanf("%d", &date) == 1 && date <= months[i-1].days && date >= 1)
    {
        total = total - (ThisMonth - date);
        printf("The total days of these months before your date are %d days.\n",total); //输出最终天数
    }
    else
        printf("Your input is undefined.\n");

    return 0;
}

 

3.

#include 
#include 

char *s_gets(char *st, int n);

#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS  100

struct book {
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};

int main(void)
{
    struct book library[MAXBKS];
    int count = 0;
    int index;

    printf("Please enter the book title.\n");
    printf("Please [enter] at the start of a line to stop.\n");
    while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0')
    {
        printf("Now enter the author.\n");
        s_gets(library[count].author, MAXAUTL);
        printf("Now enter the value.\n");
        scanf("%f", &library[count++].value);
        while (getchar() != '\n')
            continue;
        if (count < MAXBKS)
            printf("Enter the next title.\n");
    }

    if (count > 0) {
        printf("Here is the list of your books :\n");
        printf("Array by original :\n"); //原始排序
        for (index = 0; index < count; index++)
            printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
        printf("\n");

        printf("Array by title :\n");  //按标题排序
        for (int i = 0; i < count; i++) {
            for (int j = i + 1; j < count; j++) {
                struct book temp;
                if (strcmp(library[i].title, library[j].title) > 0) {
                    temp = library[i];
                    library[i] = library[j];
                    library[j] = temp;
                }
            }
        }
        for (index = 0; index < count; index++)
            printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
        printf("\n");

        printf("Array by value :\n"); //按价格排序
        for (int i = 0; i < count; i++) {
            for (int j = i + 1; j < count; j++) {
                struct book temp;
                if (library[i].value > library[j].value) {
                    temp = library[i];
                    library[i] = library[j];
                    library[j] = temp;
                }
            }
        }
        for (index = 0; index < count; index++)
            printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value);
        printf("\n");
    }
    else
        printf("No books? Too bad.\n");

    return 0;
}

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

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

 

4.

#include 
#define SECLEN 64
#define NAMELEN 32

struct name_info {
    char lname[NAMELEN]; //名
    char mname[NAMELEN]; //中间名
    char fname[NAMELEN]; //姓
};

struct info {
    char sec_num[SECLEN];
    struct name_info name;
};

void print(struct info informa[5]);
void p_print(struct info *);

int main(void)
{
    struct info * pt;

    struct info information[5] = {
            {"302039823", {"Dribble", "Flossie", "M"}},
            {"302039824", {"Owen", "", "Michale"}},
            {"302039825", {"Jone", "Jimmy", "J"}},
            {"302039826", {"Bob", "", "Mary"}},
            {"302039827", {"Jack", "And", "Him"}}
    }; //创建并初始化一个内含五个元素的结构数组
    pt = information;

    print(information);
    puts("*********************");
    puts("The other method :");
    p_print(pt);

    return 0;
}

void print(struct info informa[])
{
    int count;

    for(count = 0; count < 5; count++)
    {
        if(informa[count].name.mname[0] == '\0')
            printf("%s, %s -- %s\n", informa[count].name.fname, informa[count].name.lname, informa[count].sec_num);
        else
            printf("%s, %s %c. -- %s\n", informa[count].name.fname, informa[count].name.lname, informa[count].name.mname[0], informa[count].sec_num);
    }
}

void p_print(struct info * pst)
{
    int i = 0;

    while(i < 5)
    {
        if (pst->name.mname[0] == '\0')
            printf("%s, %s -- %s\n", pst->name.fname, pst->name.lname, pst->sec_num);
        else
            printf("%s, %s %c. -- %s\n", pst->name.fname, pst->name.lname, pst->name.mname[0], pst->sec_num);

        i++;
        pst++;
    }
}

 

5.

#include 
#define NAMELEN 32
#define CSIZE 4

struct name{
    char fname[NAMELEN];
    char lname[NAMELEN];
};

struct student{
    struct name s_name;
    float grade[3];
    float average;
};

int main(void)
{
    int i;
    float total;
    float class_average;

    struct student stdu[CSIZE];

    for(i = 0; i < CSIZE; i++)
    {
        printf("Enter the first name of the student : ");
        scanf("%s", stdu[i].s_name.fname);
        getchar();

        printf("Enter the last name of the student : ");
        scanf("%s", stdu[i].s_name.lname);
        getchar();

        for(int j = 0; j < 3; j++)
        {
            printf("Enter the %dst score of the student : ", j);
            scanf("%f", &stdu[i].grade[j]);
            getchar();
        }
    }

    for(i = 0; i < CSIZE; i++)
    {
        total = 0;
        for(int j = 0; j < 3; j++)
        {
            total += stdu[i].grade[j];
        }
        stdu[i].average = total / 3;
    }

    for(i = 0; i < CSIZE; i++)
    {
        printf("Student: %s %s, grade: %.2lf, %.2lf, %.2lf, average: %.2lf\n", stdu[i].s_name.fname, stdu[i].s_name.lname,
        stdu[i].grade[0], stdu[i].grade[1], stdu[i].grade[2], stdu[i].average);
    }

    for(i = 0, total = 0; i < CSIZE; i++)
    {
        total += stdu[i].average;
    }
    class_average = total / CSIZE;
    printf("The average score of the class is %.2f", class_average);

    return 0;
}

 

6.看不懂题

 

7.

#include 
#include 
#include 
#include 
#define MAXTITL 41
#define MAXAUTL 31
#define MAXBKS 10

char * s_gets(char * st, int n);

struct book{
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
    int delete;
};

int main(void)
{
    struct book library[MAXBKS] = { {'\0', '\0', 0.0, 0} };
    int count = 0;
    int index, filecount;
    FILE *pbooks;
    int size = sizeof(struct book);

    if ((pbooks = fopen("book.dat", "r+b")) == NULL)
    {
        fputs("Can't open book.dat file\n", stderr);
        exit(-1);
    }

    rewind(pbooks);  //定位至文件开始处
    while(count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1) //fread返回值为1表示读取成功,不成功则返回0
    {
        if(count == 0)
            puts("current contents of book.dat");
        printf("%s by %s : $%.2f\n",library[count].title, library[count].author, library[count].value); //显示文件信息
        count++;
    }
    filecount = count;  //标记原本文件中所含的结构个数
    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.");
    while(count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0')
    {
        puts("Now enter the author.");
        s_gets(library[count].author, MAXAUTL);
        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);
        fwrite(&library[filecount], size, count - filecount, pbooks); //已有filecount个文件已存在,则从第filecount+1个文件的地址开始写入,且每个单元大小为size,一共写入count-filecount个单元到pbooks指定的文件中

    }
    else
        puts("No books? Too bad.\n");

    while(1)
    {
        int choice;
        char ch;

        printf("Which book do you want to delete or modify (-1 to quit)?\n");
        scanf("%d", &choice);
        getchar();
        if(choice == -1)
        {
            break;
        }
        printf("[D]elete or [M]odify?\n");
        scanf("%c",&ch);
        getchar();
        ch = toupper(ch);
        if(ch == 'D')
        {
            library[choice-1].delete = 1;
            printf("The information has been deleted.\n");
        }
        if(ch == 'M')
        {
            printf("Please enter the book title.\n");
            s_gets(library[choice-1].title, MAXTITL);
            printf("Now enter the author.\n");
            s_gets(library[choice-1].author, MAXAUTL);
            printf("Now enter the value.\n");
            scanf("%f", &library[choice-1].value);
            while (getchar() != '\n')
            {
                continue;
            }
        }
    }
    fclose(pbooks);

    if((pbooks = fopen("book.dat", "w")) == NULL)
    {
        fputs("Can't open the file book.dat\n",stderr);
        exit(-1);
    }
    for(int i = 0; i < count; i++)
    {
        if(library[i].delete != 1)
            fwrite(&library[i], size, 1, pbooks);  //文件清空了,但是数据流还在内存中,可以再向文件中写入
    }
    puts("Done.\n");
    fclose(pbooks);

    return 0;
}

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

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

 

8.

#include 
#include 
#define LEN 64

struct information{
    char seat_num[LEN];
    int sold;
    char fname[LEN];
    char lname[LEN];
};   //sold表示票有没有售出,售出为1,未售出为0

void ShowEmptySeats(struct information *);
void ShowList(struct information *);
void ShowAlphabetical(struct information *);
void AssignSeat(struct information *);
void DeleteSeat(struct information *);

int main(void)
{
    struct information info[12] = {{"", 0, "", ""}};
    char choice;


    while(1)
    {
        printf("To choose a function, enter its letter lable:\n");
        printf("a) Show number of empty seats\n");
        printf("b) Show list of empty seats\n");
        printf("c) Show alphabetical list of seats\n");
        printf("d) Assign a customer to a seat assignment\n");
        printf("e) Delete a seat assignment\n");
        printf("f) Quit\n");

        scanf("%c", &choice);
        getchar();

        if(choice == 'f')
            break;

        switch (choice)
        {
            case 'a':
                ShowEmptySeats(info);
                break;

            case 'b':
                ShowList(info);
                break;

            case 'c':
                ShowAlphabetical(info);
                break;

            case 'd':
                AssignSeat(info);
                break;

            case 'e':
                DeleteSeat(info);
                break;

            default:
                break;
        }
    }

    return 0;
}

void ShowEmptySeats(struct information * pt)
{
    int i;
    int seats = 0;

    for(i = 0; i < 12; i++)
    {
        if((*pt).sold == 0)
        {
            seats++;
        }
        pt++;
    }
    printf("Flight still gets %d empty seats.\n", seats);
}

void ShowList(struct information * pt)
{
    int i;

    for(i = 0; i < 12; i++)
    {
        if((*pt).sold == 0)
        {
            printf("Flight %d still gets empty seats.\n", i);
        }
        pt++;
    }
}

void ShowAlphabetical(struct information * pt)  //应该是按照名字的顺序排序
{
    struct information temp;
    int i;

    for(i = 0; i < 12; i++)
    {
        if(strcmp(pt[i].fname, pt[i+1].fname) > 0)
        {
            temp = pt[i];
            pt[i] = pt[i+1];
            pt[i+1] = temp;
        }
    }
    for(i = 0; i < 12; i++)
    {
        printf("%s %s : %s\n", pt[i].fname, pt[i].lname, pt[i].seat_num);
    }
}

void AssignSeat(struct information * pt)
{
    int i;

    printf("Choose a airplane :");
    scanf("%d", &i);
    printf("Enter the first name of the customer :");
    scanf("%s", pt[i].fname);
    printf("Enter the last name of the customer :");
    scanf("%s", pt[i].lname);
    printf("Choose a seat :");
    scanf("%s", pt[i].seat_num);
}

void DeleteSeat(struct information * pt)
{
    char num[LEN];
    int i;
    struct information temp = {"", 0, "", ""};
    int whether = 0;

    printf("Enter the seat number you want to delete :");
    scanf("%s", num);
    for(i = 0; i < 12; i++)
    {
        if(strcmp(pt[i].seat_num, num) == 0)
        {
            pt[i] = temp;
            whether = 1;
        }
    }
    if(whether)
    {
        printf("%d seat has been deleted.\n", i);
    }
    else
    {
        printf("No seat has been found.\n");
    }
}

 

9.

#include 
#include 
#define LEN 64

struct information{
    char seat_num[LEN];
    int sold;
    char fname[LEN];
    char lname[LEN];
};   //sold表示票有没有售出,售出为1,未售出为0

void ShowEmptySeats(struct information *);
void ShowList(struct information *);
void ShowAlphabetical(struct information *);
void AssignSeat(struct information *);
void DeleteSeat(struct information *);

int main(void)
{
    struct information info[4][12] = {{{"", 0, "", ""}}};
    char choice;
    int flight;
    int num;

    printf("Choose a flight 102 311 444 or 519 (0 to quit): ");
    while(1)
    {
        scanf("%d", &flight);
        getchar(); //接收换行符
        if(flight == 0)
            break;
        if (flight == 102 || flight == 311 || flight == 444 || flight == 519)
        {
            if(flight == 102)
                num = 1;
            if(flight == 311)
                num = 2;
            if(flight == 444)
                num = 3;
            if(flight == 519)
                num = 4;
            while (1)
            {
                printf("To choose a function, enter its letter lable:\n");
                printf("a) Show number of empty seats\n");
                printf("b) Show list of empty seats\n");
                printf("c) Show alphabetical list of seats\n");
                printf("d) Assign a customer to a seat assignment\n");
                printf("e) Delete a seat assignment\n");
                printf("f) Back to the upper menu\n");

                scanf("%c", &choice);
                getchar();

                if (choice == 'f')
                    break;

                switch (choice) {
                    case 'a':
                        ShowEmptySeats(info[num]);
                        break;

                    case 'b':
                        ShowList(info[num]);
                        break;

                    case 'c':
                        ShowAlphabetical(info[num]);
                        break;

                    case 'd':
                        AssignSeat(info[num]);
                        break;

                    case 'e':
                        DeleteSeat(info[num]);
                        break;

                    default:
                        break;
                }
            } //内层while结束处
            printf("Choose another flight (0 to quit) : ");
            scanf("%d", &flight);
            getchar();
            if(flight == 0)
                break;
        }
        else
        {
            printf("No flight has been found, please choose again (102 311 444 or 519) : ");
            continue;
        }
    }

    return 0;
}

void ShowEmptySeats(struct information * pt)
{
    int i;
    int seats = 0;

    for(i = 0; i < 12; i++)
    {
        if((*pt).sold == 0)
        {
            seats++;
        }
        pt++;
    }
    printf("Flight still gets %d empty seats.\n", seats);
}

void ShowList(struct information * pt)
{
    int i;

    for(i = 0; i < 12; i++)
    {
        if((*pt).sold == 0)
        {
            printf("Flight %d still gets empty seats.\n", i);
        }
        pt++;
    }
}

void ShowAlphabetical(struct information * pt)  //应该是按照名字的顺序排序
{
    struct information temp;
    int i;

    for(i = 0; i < 12; i++)
    {
        if(strcmp(pt[i].fname, pt[i+1].fname) > 0)
        {
            temp = pt[i];
            pt[i] = pt[i+1];
            pt[i+1] = temp;
        }
    }
    for(i = 0; i < 12; i++)
    {
        printf("%s %s : %s\n", pt[i].fname, pt[i].lname, pt[i].seat_num);
    }
}

void AssignSeat(struct information * pt)
{
    int i;

    printf("Choose a airplane :");
    scanf("%d", &i);
    printf("Enter the first name of the customer :");
    scanf("%s", pt[i].fname);
    printf("Enter the last name of the customer :");
    scanf("%s", pt[i].lname);
    printf("Choose a seat :");
    scanf("%s", pt[i].seat_num);
}

void DeleteSeat(struct information * pt)
{
    char num[LEN];
    int i;
    struct information temp = {"", 0, "", ""};
    int whether = 0;

    printf("Enter the seat number you want to delete :");
    scanf("%s", num);
    for(i = 0; i < 12; i++)
    {
        if(strcmp(pt[i].seat_num, num) == 0)
        {
            pt[i] = temp;
            whether = 1;
        }
    }
    if(whether)
    {
        printf("%d seat has been deleted.\n", i);
    }
    else
    {
        printf("No seat has been found.\n");
    }
}

 

10.

#include 
#include 

int SumUp(int, int);

int main(void)
{
    int result1, result2;
    int (*pt)(int, int); //申明一个指向SumUp函数的指针

    pt = SumUp;
    result1 = pt(5,6);
    printf("%The sum of 5 and 6 is %d\n", result1);
    result2 = (*pt)(3,4);
    printf("The sum of 3 and 4 is %d", result2);

    return 0;
}

int SumUp(int a, int b)
{
    return a+b;
}

 

11.

#include 

double sqrt(double);
void transform(double *, double *, int, double (*fun)(double));

int main(void)
{
    double source[5] = {2.2,4,5,6.3,0.1};
    double target[5];

    transform(source, target, 5, sqrt);
    for(int i = 0; i < 5; i++)
    {
        printf("Target[%d] = %.4f\n", i, target[i]);
    }

    return 0;
}

double sqrt(double x)
{
    return (x * x);
}

void transform(double * sou, double * tar, int n, double (*fun)(double))
{
    int i;

    for(i = 0; i < n; i++)
    {
        tar[i] = fun(sou[i]);
    }
}

 

你可能感兴趣的:(C Primer Plus第六版 第十四章编程练习)