用函数调用改写学生成绩 c语言
时间: 2024-06-19 21:04:36 浏览: 114
将学生成绩的记录存储到一个结构体数组中,每个结构体包含学生的姓名、学号和成绩等信息。然后通过函数调用实现对学生成绩的操作,例如添加新的学生成绩、删除已有的学生成绩、查询某个学生的成绩、计算所有学生的平均成绩等。以下是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
struct student {
char name[20];
int id;
float score;
};
struct student students[MAX_STUDENTS];
int num_students = 0;
void add_student() {
if (num_students >= MAX_STUDENTS) {
printf("Error: too many students!\n");
return;
}
struct student s;
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter student id: ");
scanf("%d", &s.id);
printf("Enter student score: ");
scanf("%f", &s.score);
students[num_students] = s;
num_students++;
}
void delete_student() {
int id;
printf("Enter student id to delete: ");
scanf("%d", &id);
int i;
for (i = 0; i < num_students; i++) {
if (students[i].id == id) {
break;
}
}
if (i == num_students) {
printf("Error: student not found!\n");
return;
}
for (; i < num_students - 1; i++) {
students[i] = students[i + 1];
}
num_students--;
}
void print_student(struct student s) {
printf("%-20s %-10d %6.2f\n", s.name, s.id, s.score);
}
void query_student() {
int id;
printf("Enter student id to query: ");
scanf("%d", &id);
int i;
for (i = 0; i < num_students; i++) {
if (students[i].id == id) {
print_student(students[i]);
return;
}
}
printf("Error: student not found!\n");
}
void print_all_students() {
int i;
printf("%-20s %-10s %s\n", "Name", "ID", "Score");
for (i = 0; i < num_students; i++) {
print_student(students[i]);
}
}
float average_score() {
if (num_students == 0) {
printf("Error: no students!\n");
return 0.0;
}
float sum = 0.0;
int i;
for (i = 0; i < num_students; i++) {
sum += students[i].score;
}
return sum / num_students;
}
int main() {
int choice;
while (1) {
printf("\n1. Add student\n");
printf("2. Delete student\n");
printf("3. Query student\n");
printf("4. Print all students\n");
printf("5. Average score\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_student();
break;
case 2:
delete_student();
break;
case 3:
query_student();
break;
case 4:
print_all_students();
break;
case 5:
printf("Average score: %6.2f\n", average_score());
break;
case 6:
exit(0);
default:
printf("Error: invalid choice!\n");
break;
}
}
}
```
阅读全文