c语言统计学生成绩函数
时间: 2024-09-20 15:12:27 浏览: 33
在C语言中,为了统计学生成绩,你可以创建一个函数来计算平均分、总分、最高分和最低分。下面是一个简单的例子,假设我们有一个结构体`Student`,其中包含学生的姓名和成绩数组:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[50];
int scores[10]; // 假设最多有10门课程
} Student;
// 函数原型声明
void calculateStats(Student* student);
double average(int scores[], int num_scores);
int sum(int scores[], int num_scores);
int max_score(int scores[], int num_scores);
int min_score(int scores[], int num_scores);
// 主函数
int main() {
Student s;
// 初始化学生信息
scanf("%s", s.name);
for (int i = 0; i < 10; i++) {
scanf("%d", &s.scores[i]);
}
// 调用统计函数
calculateStats(&s);
return 0;
}
// 统计函数实现
void calculateStats(Student* student) {
double avg = average(student->scores, 10);
int total = sum(student->scores, 10);
int max = max_score(student->scores, 10);
int min = min_score(student->scores, 10);
printf("Name: %s\n", student->name);
printf("Average Score: %.2f\n", avg);
printf("Total Score: %d\n", total);
printf("Max Score: %d\n", max);
printf("Min Score: %d\n", min);
}
// 辅助函数
double average(int scores[], int num_scores) {
double sum = 0;
for (int i = 0; i < num_scores; i++) {
sum += scores[i];
}
return sum / num_scores;
}
int sum(int scores[], int num_scores) {
int result = 0;
for (int i = 0; i < num_scores; i++) {
result += scores[i];
}
return result;
}
int max_score(int scores[], int num_scores) {
int max = scores[0];
for (int i = 1; i < num_scores; i++) {
if (scores[i] > max) {
max = scores[i];
}
}
return max;
}
int min_score(int scores[], int num_scores) {
int min = scores[0];
for (int i = 1; i < num_scores; i++) {
if (scores[i] < min) {
min = scores[i];
}
}
return min;
}
```
阅读全文