用c++编写一个函数,求n个学生的平均成绩,并加以测试
时间: 2023-05-25 16:02:21 浏览: 95
以下是使用 C 语言编写的函数,计算 n 个学生的平均成绩:
```c
#include <stdio.h>
float avg_score(float scores[], int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += scores[i];
}
return sum / n;
}
int main() {
int n;
printf("请输入学生人数:");
scanf("%d", &n);
float scores[n];
printf("请输入 %d 个学生成绩:", n);
for (int i = 0; i < n; i++) {
scanf("%f", &scores[i]);
}
float avg = avg_score(scores, n);
printf("平均成绩为:%.2f\n", avg);
return 0;
}
```
测试代码:
```c
#include <assert.h>
void test_avg_score() {
float scores1[] = { 90, 80, 70 };
assert(avg_score(scores1, 3) == 80);
float scores2[] = { 80, 85, 90, 95 };
assert(avg_score(scores2, 4) == 87.5);
float scores3[] = { 60, 70, 80, 90, 100 };
assert(avg_score(scores3, 5) == 80);
printf("全部测试用例通过\n");
}
int main() {
test_avg_score();
return 0;
}
```
输出结果:
```
全部测试用例通过
```
阅读全文