#include <stdio.h> #include <string.h> #include <stdlib.h> // 定义结构体类型 struct Student { char id[10]; // 学号 char name[20]; // 姓名 char gender[10]; // 性别 int chinese; // 语文成绩 int math; // 数学成绩 int english; // 英语成绩 }; // 初始化几个学生的基本信息 struct Student students[] = { {"1001", "张三", "Male", 80, 90, 85}, {"1002", "李四", "Female", 75, 85, 90}, {"1003", "王五", "Male", 90, 80, 95}, {"1004", "赵六", "Female", 85, 95, 80}, {"1005", "钱七", "Male", 95, 85, 90} }; int count=5; // 学生数量//添加一个学生信息 void addStudent() { struct Student *new_student = (struct Student *)malloc(sizeof(struct Student)); printf("请输入学生的基本信息:\n"); printf("学号:"); scanf("%s", new_student->id); printf("姓名:"); scanf("%s", new_student->name); printf("性别:"); scanf("%s", new_student->gender); printf("语文成绩:"); scanf("%d", &new_student->chinese); printf("数学成绩:"); scanf("%d", &new_student->math); printf("英语成绩:"); scanf("%d", &new_student->english); students[count++] = *new_student; count=count+1; free(new_student); }修改这段代码
时间: 2023-07-13 11:22:49 浏览: 46
有几处需要修改:
1. 在结构体定义中,将成绩的数据类型从 int 修改为 float,以允许输入小数点后的分数。
2. 在添加学生信息的函数 addStudent() 中,将 count 的计算方式改为 count+1,以避免重复计算。
3. 在添加学生信息的函数 addStudent() 中,应该在使用完动态分配的内存后,使用 free() 函数释放内存。
下面是修改后的代码:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student {
char id[10]; // 学号
char name[20]; // 姓名
char gender[10]; // 性别
float chinese; // 语文成绩
float math; // 数学成绩
float english; // 英语成绩
};
struct Student students[] = {
{"1001", "张三", "Male", 80, 90, 85},
{"1002", "李四", "Female", 75, 85, 90},
{"1003", "王五", "Male", 90, 80, 95},
{"1004", "赵六", "Female", 85, 95, 80},
{"1005", "钱七", "Male", 95, 85, 90}
};
int count = 5; // 学生数量
void addStudent() {
struct Student *new_student = (struct Student *)malloc(sizeof(struct Student));
printf("请输入学生的基本信息:\n");
printf("学号:");
scanf("%s", new_student->id);
printf("姓名:");
scanf("%s", new_student->name);
printf("性别:");
scanf("%s", new_student->gender);
printf("语文成绩:");
scanf("%f", &new_student->chinese);
printf("数学成绩:");
scanf("%f", &new_student->math);
printf("英语成绩:");
scanf("%f", &new_student->english);
students[count++] = *new_student;
free(new_student);
}
int main() {
addStudent();
for (int i = 0; i < count; i++) {
printf("学号:%s 姓名:%s 性别:%s 语文成绩:%.2f 数学成绩:%.2f 英语成绩:%.2f\n",
students[i].id, students[i].name, students[i].gender, students[i].chinese, students[i].math, students[i].english);
}
return 0;
}
```