MST

星途 面试题库

面试题:C语言结构体与回调函数基础应用

假设有一个结构体 `struct Student`,包含成员 `name`(字符数组,长度为50)、`age`(整数)和 `score`(浮点数)。请编写一个函数 `printStudent`,它接受 `struct Student` 类型的指针作为参数,并将学生信息打印出来。同时,编写一个回调函数 `compareScore`,用于比较两个学生的分数大小,返回值为1表示第一个学生分数高, - 1表示第二个学生分数高,0表示分数相等。最后,编写一个函数 `sortStudentsByScore`,它接受一个 `struct Student` 类型的数组指针和数组长度,使用回调函数 `compareScore` 对学生数组按分数进行排序(可使用冒泡排序等简单排序算法)。
36.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义结构体
struct Student {
    char name[50];
    int age;
    float score;
};

// 打印学生信息的函数
void printStudent(struct Student *student) {
    printf("Name: %s, Age: %d, Score: %.2f\n", student->name, student->age, student->score);
}

// 比较分数的回调函数
int compareScore(struct Student *student1, struct Student *student2) {
    if (student1->score > student2->score) {
        return 1;
    } else if (student1->score < student2->score) {
        return -1;
    } else {
        return 0;
    }
}

// 按分数排序的函数
void sortStudentsByScore(struct Student *students, int length, int (*compare)(struct Student *, struct Student *)) {
    int i, j;
    struct Student temp;
    for (i = 0; i < length - 1; i++) {
        for (j = 0; j < length - i - 1; j++) {
            if (compare(&students[j], &students[j + 1]) == 1) {
                temp = students[j];
                students[j] = students[j + 1];
                students[j + 1] = temp;
            }
        }
    }
}

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

int main() {
    struct Student students[] = {
        {"Alice", 20, 85.5},
        {"Bob", 21, 90.0},
        {"Charlie", 19, 80.0}
    };
    int length = sizeof(students) / sizeof(students[0]);

    printf("Before sorting:\n");
    for (int i = 0; i < length; i++) {
        printStudent(&students[i]);
    }

    sortStudentsByScore(students, length, compareScore);

    printf("\nAfter sorting:\n");
    for (int i = 0; i < length; i++) {
        printStudent(&students[i]);
    }

    return 0;
}