我需要一个代码//把学生信息存放在txt文件中,读取数据,数据放在单链表中。 //要求可以通过ID查询某学生的各科成绩和总分及平均分 //可以通过ID查询某科成绩排名 //可以通过ID查询总分排名。 //成绩一样的排名一样。 #include <stdio.h> struct STU{ long ID; unsigned C; unsigned math; unsigned python; }; int main(void) { struct STU stu[10]; //sort by c+math+python return 0; }
时间: 2023-04-10 21:03:49 浏览: 101
以下是一个示例代码,实现了将学生信息存储在txt文件中,读取数据并将其放入单链表中。同时,还可以通过ID查询某学生的各科成绩和总分及平均分,通过ID查询某科成绩排名,以及通过ID查询总分排名。注意,成绩相同的学生排名也相同。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_ID_LEN 10
#define MAX_SUBJECTS 5
// 学生信息结构体
typedef struct student {
char name[MAX_NAME_LEN]; // 姓名
char id[MAX_ID_LEN]; // 学号
int scores[MAX_SUBJECTS]; // 各科成绩
int total_score; // 总分
float avg_score; // 平均分
struct student *next; // 指向下一个学生的指针
} Student;
// 读取txt文件中的学生信息,返回一个指向链表头的指针
Student* read_students_from_file(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return NULL;
}
Student *head = NULL;
Student *tail = NULL;
char line[100];
while (fgets(line, sizeof(line), fp) != NULL) {
Student *s = (Student*)malloc(sizeof(Student));
sscanf(line, "%s %s %d %d %d %d %d", s->name, s->id, &s->scores[0], &s->scores[1], &s->scores[2], &s->scores[3], &s->scores[4]);
s->total_score = 0;
for (int i = 0; i < MAX_SUBJECTS; i++) {
s->total_score += s->scores[i];
}
s->avg_score = (float)s->total_score / MAX_SUBJECTS;
s->next = NULL;
if (head == NULL) {
head = s;
tail = s;
} else {
tail->next = s;
tail = s;
}
}
fclose(fp);
return head;
}
// 根据学号查找学生,返回一个指向该学生的指针
Student* find_student_by_id(Student *head, char *id) {
Student *p = head;
while (p != NULL) {
if (strcmp(p->id, id) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
// 根据学号和科目编号查找该科目的成绩排名,返回排名
int find_rank_by_subject(Student *head, char *id, int subject) {
Student *p = head;
int rank = 1;
while (p != NULL) {
if (strcmp(p->id, id) != 0 && p->scores[subject] > find_student_by_id(head, id)->scores[subject]) {
rank++;
}
p = p->next;
}
return rank;
}
// 根据学号查找总分排名,返回排名
int find_rank_by_total_score(Student *head, char *id) {
Student *p = head;
int rank = 1;
while (p != NULL) {
if (strcmp(p->id, id) != 0 && p->total_score > find_student_by_id(head, id)->total_score) {
rank++;
}
p = p->next;
}
return rank;
}
int main() {
Student *head = read_students_from_file("students.txt");
// 测试查找学生信息
Student *s = find_student_by_id(head, "1001");
if (s != NULL) {
printf("Name: %s\n", s->name);
printf("ID: %s\n", s->id);
printf("Scores: ");
for (int i = 0; i < MAX_SUBJECTS; i++) {
printf("%d ", s->scores[i]);
}
printf("\n");
printf("Total score: %d\n", s->total_score);
printf("Average score: %.2f\n", s->avg_score);
}
// 测试查找科目排名
int rank = find_rank_by_subject(head, "1001", 2);
printf("Rank of subject 2 for student 1001: %d\n", rank);
// 测试查找总分排名
rank = find_rank_by_total_score(head, "1001");
printf("Rank of total score for student 1001: %d\n", rank);
return 0;
}
阅读全文