把上述代码用C语言写出
时间: 2024-10-21 13:04:30 浏览: 16
在C语言中,由于没有内置的对象或类的概念,我们通常会使用结构体(struct)来模拟这种行为。下面是一个简单的`Student`结构体和相关的函数实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char studentId[50]; // 学号
char name[50]; // 姓名
int scores[3]; // 三门课程的成绩
} Student;
// 初始化学生
void createStudent(Student* student, char* studentId, char* name) {
strncpy(student->studentId, studentId, sizeof(student->studentId));
strncpy(student->name, name, sizeof(student->name));
student->scores[0] = -1; // 初始值为未设置
student->scores[1] = -1;
student->scores[2] = -1;
}
// 设置单门课程成绩
void setScore(Student* student, int courseIndex, int score) {
if (courseIndex >= 0 && courseIndex < 3) {
student->scores[courseIndex] = score;
} else {
printf("Invalid course index.\n");
}
}
// 获取单门课程成绩
int getScore(Student* student, int courseIndex) {
if (courseIndex >= 0 && courseIndex < 3) {
return student->scores[courseIndex];
} else {
printf("Invalid course index.\n");
return -1;
}
}
// 计算平均成绩
float calculateAverage(const Student* student) {
int total = 0;
for (int i = 0; i < 3; i++) {
if (student->scores[i] != -1) {
total += student->scores[i];
}
}
return (total > 0) ? (float)total / 3 : -1; // 防止除以零
}
// 打印学生信息
void printStudent(const Student* student) {
printf("Student ID: %s\n", student->studentId);
printf("Name: %s\n", student->name);
printf("Scores: %d %d %d\n", student->scores[0], student->scores[1], student->scores[2]);
}
int main() {
Student student;
createStudent(&student, "123456", "张三");
// 设置和获取成绩示例
setScore(&student, 0, 85);
setScore(&student, 2, 92);
printf("Score for math: %d\n", getScore(&student, 0));
// 计算平均成绩
float avg = calculateAverage(&student);
printf("Average Score: %.2f\n", avg);
return 0;
}
```
注意:这个C版本假设输入的分数都是整数,并且设置了初始值 `-1` 来标记未设置的课程。在实际应用中,你可能需要调整这些细节。
阅读全文