MST

星途 面试题库

面试题:C语言结构体嵌套与复杂回调函数应用

定义一个结构体 `struct Course`,包含课程名称(字符数组,长度为50)和学分(整数)。再定义一个结构体 `struct Student`,包含学生姓名(字符数组,长度为50)、年龄(整数)以及一个 `struct Course` 类型的指针数组,用于表示学生所选的课程(假设最多选5门课程)。编写一个函数 `addCourse`,用于向学生的课程数组中添加一门课程。编写一个回调函数 `calculateTotalCredit`,用于计算一个学生所选课程的总学分。最后,编写一个函数 `findStudentWithMaxCredit`,它接受一个 `struct Student` 类型的数组指针和数组长度,使用回调函数 `calculateTotalCredit` 找出总学分最高的学生,并返回该学生的姓名。
41.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义Course结构体
struct Course {
    char name[50];
    int credit;
};

// 定义Student结构体
struct Student {
    char name[50];
    int age;
    struct Course* courses[5];
    int courseCount;
};

// 向学生的课程数组中添加一门课程
void addCourse(struct Student* student, struct Course* course) {
    if (student->courseCount < 5) {
        student->courses[student->courseCount++] = course;
    } else {
        printf("该学生已选满5门课程,无法添加更多课程。\n");
    }
}

// 计算一个学生所选课程的总学分
int calculateTotalCredit(struct Student* student) {
    int totalCredit = 0;
    for (int i = 0; i < student->courseCount; i++) {
        totalCredit += student->courses[i]->credit;
    }
    return totalCredit;
}

// 找出总学分最高的学生,并返回该学生的姓名
const char* findStudentWithMaxCredit(struct Student* students, int length) {
    int maxCredit = 0;
    const char* maxStudentName = "";
    for (int i = 0; i < length; i++) {
        int currentCredit = calculateTotalCredit(&students[i]);
        if (currentCredit > maxCredit) {
            maxCredit = currentCredit;
            maxStudentName = students[i].name;
        }
    }
    return maxStudentName;
}

你可以使用以下方式调用这些函数:

int main() {
    struct Course course1 = {"数学", 3};
    struct Course course2 = {"英语", 2};
    struct Course course3 = {"计算机科学", 4};

    struct Student student1 = {"Alice", 20, {}, 0};
    struct Student student2 = {"Bob", 21, {}, 0};

    addCourse(&student1, &course1);
    addCourse(&student1, &course2);
    addCourse(&student2, &course3);

    const char* maxCreditStudent = findStudentWithMaxCredit(&student1, 2);
    printf("总学分最高的学生是: %s\n", maxCreditStudent);

    return 0;
}

代码说明

  1. 结构体定义

    • struct Course 结构体包含课程名称 name 和学分 credit
    • struct Student 结构体包含学生姓名 name、年龄 age、一个 struct Course 类型的指针数组 courses 以及当前已选课程数量 courseCount
  2. addCourse 函数

    • 用于向学生的课程数组中添加一门课程,如果课程数量未达到5门,则添加成功;否则提示已选满。
  3. calculateTotalCredit 回调函数

    • 计算一个学生所选课程的总学分,遍历学生的课程数组,累加每门课程的学分。
  4. findStudentWithMaxCredit 函数

    • 接受一个 struct Student 类型的数组指针和数组长度,使用 calculateTotalCredit 回调函数找出总学分最高的学生,并返回该学生的姓名。
  5. main 函数

    • 创建了一些课程和学生实例,并调用上述函数进行测试。