Highest grade in subject : 100.00 (by xxx)这段代码如何在C语言中复刻
时间: 2024-12-16 20:32:59 浏览: 2
要复刻一个类似的功能来查找最高成绩及其对应的学生,在 C 语言中可以编写如下示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100
#define NAME_LENGTH 50
typedef struct {
char name[NAME_LENGTH];
float grade;
} Student;
void addStudent(Student students[], int *count, const char *name, float grade) {
if (*count >= MAX_STUDENTS) {
printf("Error: Maximum number of students reached.\n");
return;
}
strcpy(students[*count].name, name);
students[*count].grade = grade;
(*count)++;
}
void findHighestGrade(const Student students[], int count, char resultName[NAME_LENGTH], float *resultGrade) {
*resultGrade = -1.0;
for (int i = 0; i < count; i++) {
if (students[i].grade > *resultGrade) {
*resultGrade = students[i].grade;
strcpy(resultName, students[i].name);
}
}
}
int main() {
Student students[MAX_STUDENTS];
int studentCount = 0;
// 添加一些学生和成绩
addStudent(students, &studentCount, "Alice", 95.00);
addStudent(students, &studentCount, "Bob", 85.00);
addStudent(students, &studentCount, "Charlie", 100.00);
char highestName[NAME_LENGTH];
float highestGrade;
findHighestGrade(students, studentCount, highestName, &highestGrade);
if (highestGrade != -1.0) {
printf("Highest grade in subject: %.2f (by %s)\n", highestGrade, highestName);
} else {
printf("No students found.\n");
}
return 0;
}
```
### 解释
1. **定义结构体**:`Student` 结构体用于存储学生的姓名和成绩。
2. **添加学生函数**:`addStudent` 函数将学生的信息添加到数组中,并增加计数器。
3. **查找最高成绩函数**:`findHighestGrade` 函数遍历学生数组,找到最高成绩及其对应的学生姓名。
4. **主函数**:在 `main` 函数中,首先添加几个学生和他们的成绩,然后调用 `findHighestGrade` 函数来查找并打印最高成绩及其对应的学生姓名。
这个示例展示了如何在 C 语言中实现查找最高成绩的功能。你可以根据需要扩展和修改这个代码。
阅读全文