使用结构体储存学生信息(包括学号姓名三门成绩和总分)要求实现对学生信息的修改和删除操作,最多50名学生
时间: 2024-03-10 16:44:07 浏览: 66
好的,我可以帮你实现这个需求。以下是一份示例代码,你可以参考它:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 50
#define MAX_NAME_LENGTH 20
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int score1;
int score2;
int score3;
int total;
} Student;
Student students[MAX_STUDENTS];
int num_students = 0;
int add_student(int id, char *name, int score1, int score2, int score3) {
if (num_students >= MAX_STUDENTS) {
printf("Error: Too many students.\n");
return -1;
}
// Check if student with the same ID already exists
for (int i = 0; i < num_students; i++) {
if (students[i].id == id) {
printf("Error: Student with ID %d already exists.\n", id);
return -1;
}
}
// Add new student
Student new_student;
new_student.id = id;
strcpy(new_student.name, name);
new_student.score1 = score1;
new_student.score2 = score2;
new_student.score3 = score3;
new_student.total = score1 + score2 + score3;
students[num_students++] = new_student;
return 0;
}
int find_student_index(int id) {
for (int i = 0; i < num_students; i++) {
if (students[i].id == id) {
return i;
}
}
return -1;
}
int update_student(int id, char *name, int score1, int score2, int score3) {
int index = find_student_index(id);
if (index == -1) {
printf("Error: No student with ID %d found.\n", id);
return -1;
}
Student *student = &students[index];
strcpy(student->name, name);
student->score1 = score1;
student->score2 = score2;
student->score3 = score3;
student->total = score1 + score2 + score3;
return 0;
}
int delete_student(int id) {
int index = find_student_index(id);
if (index == -1) {
printf("Error: No student with ID %d found.\n", id);
return -1;
}
// Shift elements to the left to remove the student
for (int i = index; i < num_students - 1; i++) {
students[i] = students[i+1];
}
num_students--;
return 0;
}
void print_student(Student *student) {
printf("%d\t%s\t%d\t%d\t%d\t%d\n", student->id, student->name,
student->score1, student->score2, student->score3, student->total);
}
void print_students() {
printf("ID\tName\tScore1\tScore2\tScore3\tTotal\n");
for (int i = 0; i < num_students; i++) {
print_student(&students[i]);
}
}
int main() {
// Add some sample students
add_student(1001, "Alice", 80, 90, 85);
add_student(1002, "Bob", 70, 85, 75);
add_student(1003, "Charlie", 90, 95, 92);
// Print all students
printf("Initial students:\n");
print_students();
// Update a student
update_student(1002, "Bob Smith", 75, 90, 80);
printf("\nAfter updating student 1002:\n");
print_students();
// Add a new student
add_student(1004, "David", 85, 80, 90);
printf("\nAfter adding student 1004:\n");
print_students();
// Delete a student
delete_student(1003);
printf("\nAfter deleting student 1003:\n");
print_students();
return 0;
}
```
这份代码定义了一个 `Student` 结构体来储存学生信息,并使用了一个全局的 `students` 数组来储存所有学生。在 `main` 函数中调用了一些示例操作,包括添加、修改和删除学生,并且在每次操作后都打印了所有学生的信息。你可以根据自己的需求进行修改和扩展,例如添加输入功能或者文件读写功能等。