面试题答案
一键面试#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;
}