首页  > 考试管理  > c中如何修改成绩

c中如何修改成绩

2025-04-30 17:49:20
何老师
何老师已认证

何老师为您分享以下优质知识

在C语言中修改学生成绩可以通过多种方式实现,以下是常见的方法及示例代码:

一、使用数组存储成绩

基本实现

通过数组存储学生成绩,通过索引访问和修改元素。需注意数组大小固定,需动态管理容量。

```c

include

define MAX_SIZE 100

void modify_score(int scores[], int n, int index, int new_score) {

if (index >

= 0 && index < n) {

scores[index] = new_score;

} else {

printf("索引超出范围!n");

}

}

int main() {

int scores[MAX_SIZE] = {80, 78, 92};

int n = 3;

printf("当前成绩:");

for (int i = 0; i < n; i++) {

printf("%4d ", scores[i]);

}

printf("n");

int index, new_score;

printf("输入要修改的学生成绩索引(0-%d)及新分数:", n - 1);

scanf("%d %d", &index, &new_score);

modify_score(scores, n, index, new_score);

printf("修改后成绩:");

for (int i = 0; i < n; i++) {

printf("%4d ", scores[i]);

}

printf("n");

return 0;

}

```

动态数组扩展

若需动态添加成绩,可结合`realloc`函数调整数组大小。

二、使用链表存储成绩

链表适合动态管理数据,支持高效插入和删除操作。

```c

include

include

typedef struct Student {

int score;

struct Student* next;

} Student;

void modify_score(Node head, int index, int new_score) {

Node* current = *head;

Node* prev = NULL;

int count = 0;

while (current != NULL) {

if (count == index) {

current->

score = new_score;

return;

}

prev = current;

current = current->

next;

count++;

}

printf("索引超出范围!n");

}

void add_score(Node head, int score) {

Node* new_node = (Node*)malloc(sizeof(Student));

new_node->

score = score;

new_node->

next = *head;

*head = new_node;

}

void print_scores(Node* head) {

Node* current = head;

while (current != NULL) {

printf("%d ", current->

score);

current = current->

next;

}

printf("n");

}

int main() {

Node* head = NULL;

// 添加初始成绩

add_score(&head, 80);

add_score(&head, 78);

add_score(&head, 92);

printf("初始成绩:");

print_scores(head);

int index, new_score;

printf("输入要修改的学生成绩索引(0)及新分数:");

scanf("%d %d", &index, &new_score);

modify_score(&head, index, new_score);

printf("修改后成绩:");

print_scores(head);

// 释放链表内存

Node* current = head;

while (current != NULL) {

Node* temp = current;

current = current->

next;

free(temp);

}

return 0;

}

```

三、使用文件存储成绩

通过文件读写操作实现数据持久化。

```c

include

include

define MAX_STUDENTS 100

typedef struct Student {

int score;

char name;

} Student;

void modify_score_file(Student* students, int n, int index, int new_score) {

for (int i = 0; i < n; i++) {

if (i == index) {

students[i].score = new_score;

return;

}

}

printf("索引超出范围!n");

}

void save_scores_to_file(Student* students, int n) {

FILE* file = fopen("scores.txt", "wb");

if (file == NULL) {

printf("无法打开文件!n");

return;

}

for (int i = 0; i < n; i++) {

fprintf(file, "%s %d

", students[i].name, students[i].score);

}

fclose(file);

}

void load_scores_from_file(Student* students, int* n) {

FILE* file = fopen("scores.txt", "