头歌C语言题目描述:本关任务:使用结构体储存学生信息(包括学号,姓名,3 门课程成绩,总分),要求实现对学生信息修改和删除操作,最多50名学生。
时间: 2025-06-23 09:25:11 浏览: 11
### C语言使用结构体存储、修改和删除学生信息
为了满足需求,可以设计一个程序框架来处理最多50名学生的信息。此程序利用结构体定义每位学生的数据成员,并通过函数实现增加、显示、修改以及删除功能。
#### 定义结构体
首先创建名为`Student`的结构体用于保存单个学生的数据字段:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 50
typedef struct {
int id;
char name[50];
float scores[3]; // Three course scores
float total_score; // Sum of three courses' scores
} Student;
// Array to hold up to 50 students
Student studentList[MAX_STUDENTS];
int count = 0; // Counter for the number of added students
```
#### 添加新记录
当向列表中添加新的学生条目时,需确保不超过最大容量限制并计算总分数:
```c
void add_student() {
if (count >= MAX_STUDENTS) {
printf("Cannot add more than %d students.\n", MAX_STUDENTS);
return;
}
Student newStu;
printf("Enter ID: ");
scanf("%d", &newStu.id);
printf("Enter Name: ");
getchar(); // Clear buffer before reading string with spaces
fgets(newStu.name, sizeof(newStu.name), stdin);
newStu.name[strcspn(newStu.name, "\n")] = '\0'; // Remove trailing newline character
float sum = 0;
for(int i=0;i<3;++i){
printf("Enter score for Course%d: ", i+1);
scanf("%f",&newStu.scores[i]);
sum += newStu.scores[i];
}
newStu.total_score=sum;
studentList[count++] = newStu;
}
```
#### 显示所有记录
遍历整个数组打印出当前已录入的学生详情[^1]:
```c
void display_students(){
if(count==0){
printf("No records found!\n");
return ;
}else{
for(int i=0;i<count;i++){
printf("\nID:%d\nName:%s\nScores:[%.2f, %.2f, %.2f]\nTotal Score=%.2f\n",
studentList[i].id,
studentList[i].name,
studentList[i].scores[0],
studentList[i].scores[1],
studentList[i].scores[2],
studentList[i].total_score );
}
}
}
```
#### 修改特定记录
允许用户指定要更新的具体项目(如某位同学的成绩)。这里假设通过学号定位目标对象进行编辑操作:
```c
void modify_student(){
int targetId;
printf("Please enter the ID you want to change:");
scanf("%d",&targetId);
bool found=false;
for(int i=0;i<count&&!found;i++)
if(studentList[i].id==targetId){
found=true;
// Modify logic here...
printf("Modifying record...\n");
for(int j=0;j<3;++j){
printf("Re-enter score for Course%d:",j+1);
scanf("%f",&studentList[i].scores[j]);
}
studentList[i].total_score=(float)(studentList[i].scores[0]+studentList[i].scores[1]+studentList[i].scores[2]);
break;
}
if(!found)
printf("Record not found or no changes made.\n");
}
```
#### 删除选定记录
提供选项让用户移除不再需要的一条或多条记录。同样依据唯一标识符——学号来进行查找匹配并执行相应动作:
```c
void delete_student(){
int del_id;
printf("Input the ID which needs deletion:\n");
scanf("%d",&del_id);
for(int i=0;i<count;i++){
if(del_id == studentList[i].id){
for(;i<count-1;i++) // Shift elements forward after removal point
studentList[i]=studentList[i+1];
count--; // Reduce size by one element since last item is now duplicated and invalid.
printf("Deletion successful.\n");
return;
}
}
printf("Failed to find matching entry for given ID.\n");
}
```
以上就是基于C语言的一个简单应用实例,展示了如何运用结构体管理一组具有相似属性的对象集合,在实际开发过程中可根据具体业务场景调整细节部分的设计思路。
阅读全文
相关推荐


















