You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.5 KiB

#include <stdio.h>
#include <string.h>
#define NUM_STUDENTS 3
#define NAME_LEN 50
typedef struct {
int id;
int class;
char name[NAME_LEN];
float scores[3];
float total;
} Student;
int compare(const void *a, const void *b) {
Student *studentA = (Student *)a;
Student *studentB = (Student *)b;
if (studentA->class != studentB->class) {
return studentA->class - studentB->class;
} else {
return studentB->total - studentA->total;
}
}
void calculateTotal(Student *student) {
student->total = student->scores[0] + student->scores[1] + student->scores[2];
}
void printStudents(Student students[], int count) {
int prevClass = -1;
int i;
for (i = 0; i < count; i++) {
if (students[i].class != prevClass) {
printf("%d", students[i].class);
prevClass = students[i].class;
} else {
printf(" ");
}
printf(" %d %s %.1f %.1f %.1f", students[i].id, students[i].name,
students[i].scores[0], students[i].scores[1], students[i].scores[2]);
if (i == NUM_STUDENTS - 1 || students[i + 1].class != students[i].class ||
students[i + 1].id != students[i].id + 1) {
printf(" modified\n");
} else {
printf("\n");
}
}
}
void modifyStudent(Student students[], int count, int id, int class, const char *name, float scores[]) {
int i;
for (i = 0; i < count; i++) {
if (students[i].id == id) {
students[i].class = class;
strncpy(students[i].name, name, NAME_LEN);
students[i].scores[0] = scores[0];
students[i].scores[1] = scores[1];
students[i].scores[2] = scores[2];
calculateTotal(&students[i]);
qsort(students, count, sizeof(Student), compare);
return;
}
}
}
int main() {
Student students[NUM_STUDENTS] = {
{10001, 11, "Zhang", {99.5, 88.5, 89.5}, 0},
{10002, 12, "Yang", {77.9, 56.5, 87.5}, 0},
{10003, 11, "Liang", {92.5, 99.0, 60.5}, 0}
};
int i;
for (i = 0; i < NUM_STUDENTS; i++) {
calculateTotal(&students[i]);
}
qsort(students, NUM_STUDENTS, sizeof(Student), compare);
int id, class;
char name[NAME_LEN];
float scores[3];
printf("\n");
scanf("%d %d %s %f %f %f", &id, &class, name, &scores[0], &scores[1], &scores[2]);
modifyStudent(students, NUM_STUDENTS, id, class, name, scores);
printStudents(students, NUM_STUDENTS);
return 0;
}