用C语言写一个学生选课系统
时间: 2023-05-14 17:05:50 浏览: 38
好的,以下是一个简单的学生选课系统的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COURSES 10
#define MAX_STUDENTS 100
typedef struct {
char name[20];
int id;
int credits;
} Course;
typedef struct {
char name[20];
int id;
int num_courses;
int courses[MAX_COURSES];
} Student;
Course courses[MAX_COURSES];
int num_courses = 0;
Student students[MAX_STUDENTS];
int num_students = 0;
void add_course(char *name, int id, int credits) {
if (num_courses >= MAX_COURSES) {
printf("Error: too many courses\n");
return;
}
Course course;
strcpy(course.name, name);
course.id = id;
course.credits = credits;
courses[num_courses++] = course;
}
void add_student(char *name, int id) {
if (num_students >= MAX_STUDENTS) {
printf("Error: too many students\n");
return;
}
Student student;
strcpy(student.name, name);
student.id = id;
student.num_courses = 0;
students[num_students++] = student;
}
void enroll_student(int student_id, int course_id) {
if (student_id < 0 || student_id >= num_students) {
printf("Error: invalid student id\n");
return;
}
if (course_id < 0 || course_id >= num_courses) {
printf("Error: invalid course id\n");
return;
}
Student *student = &students[student_id];
if (student->num_courses >= MAX_COURSES) {
printf("Error: student has too many courses\n");
return;
}
student->courses[student->num_courses++] = course_id;
}
void print_courses() {
printf("Courses:\n");
for (int i = 0; i < num_courses; i++) {
Course course = courses[i];
printf("%d: %s (%d credits)\n", course.id, course.name, course.credits);
}
}
void print_students() {
printf("Students:\n");
for (int i = 0; i < num_students; i++) {
Student student = students[i];
printf("%d: %s\n", student.id, student.name);
printf(" Courses:\n");
for (int j = 0; j < student.num_courses; j++) {
int course_id = student.courses[j];
Course course = courses[course_id];
printf(" %s\n", course.name);
}
}
}
int main() {
add_course("Math", 0, 3);
add_course("English", 1, 4);
add_course("History", 2, 3);
add_student("Alice", 0);
add_student("Bob", 1);
enroll_student(0, 0);
enroll_student(0, 1);
enroll_student(1, 1);
enroll_student(1, 2);
print_courses();
print_students();
return 0;
}