编写一个C++函数,求n个学生的平均成绩
时间: 2023-05-25 14:02:23 浏览: 79
A:
假设已知学生的成绩存储在一个数组score中,数组中有n个元素。
可以编写一个函数来计算这n个学生的平均成绩:
```
float average_score(float score[], int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += score[i];
}
return sum / n;
}
```
这个函数的参数包括一个数组score和一个整数n,函数使用一个循环来遍历数组中的所有元素,并计算它们的总和。然后,该函数返回总和除以n,得出平均值。最后返回平均值作为函数的结果。
相关问题
用c++编写一个函数,求n个学生的平均成绩,并加以测试
以下是使用 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;
}
```
输出结果:
```
全部测试用例通过
```
在C++编写一个函数,求n个学生的平均成绩,并加以测试
A:
以下是一个示例代码:
```c
#include <stdio.h>
float average(float grades[], int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += grades[i];
}
return sum / n;
}
int main() {
float grades[10] = {98, 85, 92, 76, 80, 88, 90, 95, 84, 89};
int num_of_students = 10;
printf("Average grade: %.2f\n", average(grades, num_of_students));
return 0;
}
```
该程序中,`average`函数接受一个浮点数数组`grades`和整数`n`,求出这`n`个学生的平均成绩,并返回结果。在`main`函数中,我们定义10个学生的成绩数组`grades`和学生人数`num_of_students`,然后调用`average`函数求出平均成绩并打印输出。输出结果为:
```
Average grade: 88.7
```
你可以根据需要修改`grades`数组和`num_of_students`变量的值,以测试不同情况下的平均成绩。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)