MST

星途 面试题库

面试题:C语言结构体指针作为函数参数的复杂操作

定义一个结构体 `Book`,包含 `title`(字符数组)、`author`(字符数组)、`price`(浮点数)和 `publicationYear`(整数)。编写一个函数 `updateBookPrice`,该函数接收一个 `Book` 结构体指针数组和数组的大小作为参数。在函数中,将所有出版年份在2010年之后(含2010年)的书籍价格提高10%。在 `main` 函数中初始化一个 `Book` 结构体数组,并调用 `updateBookPrice` 函数,然后打印出更新后的书籍信息。
28.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>

// 定义Book结构体
struct Book {
    char title[100];
    char author[50];
    float price;
    int publicationYear;
};

// 更新书籍价格的函数
void updateBookPrice(struct Book *books[], int size) {
    for (int i = 0; i < size; i++) {
        if (books[i]->publicationYear >= 2010) {
            books[i]->price = books[i]->price * 1.1;
        }
    }
}

int main() {
    struct Book book1 = {"C Programming Language", "Brian W. Kernighan", 29.99, 1988};
    struct Book book2 = {"Effective Java", "Joshua Bloch", 49.99, 2008};
    struct Book book3 = {"Clean Code", "Robert C. Martin", 39.99, 2008};
    struct Book book4 = {"Python Crash Course", "Eric Matthes", 34.99, 2015};

    struct Book *books[] = {&book1, &book2, &book3, &book4};
    int size = sizeof(books) / sizeof(books[0]);

    updateBookPrice(books, size);

    for (int i = 0; i < size; i++) {
        printf("Title: %s\n", books[i]->title);
        printf("Author: %s\n", books[i]->author);
        printf("Price: %.2f\n", books[i]->price);
        printf("Publication Year: %d\n\n", books[i]->publicationYear);
    }

    return 0;
}