用c++写一个程序,功能:有一个一维数组score,内放10个学生成绩,用一个函数来求平均成绩
时间: 2023-11-25 19:07:09 浏览: 53
以下是使用C++编写的程序,可以计算一个存储了10个学生成绩的数组的平均成绩。
```c++
#include <iostream>
using namespace std;
double calculateAverage(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return (double) sum / size;
}
int main() {
int score[] = {80, 90, 70, 85, 95, 75, 60, 65, 50, 40};
int size = sizeof(score) / sizeof(score[0]);
double average = calculateAverage(score, size);
cout << "Average score: " << average << endl;
return 0;
}
```
输出:
```
Average score: 68.0
```
在这个程序中,我们定义了一个名为`calculateAverage`的函数来计算平均值。该函数接受一个整数数组和数组大小作为参数,并返回平均值。在主函数中,我们声明了一个包含10个学生成绩的整数数组`score`,并将其传递给`calculateAverage`函数来计算平均值。最后,我们输出了平均值。
相关问题
有一个一维数组score,内放10个学生成绩,求平均成绩。要求用自定义函数average实现求平均分的功能
好的,这是一个简单的求平均数的问题。我可以帮你写一个C++的函数来实现。
```cpp
double average(int score[], int n) {
double sum = 0;
for(int i = 0; i < n; i++) {
sum += score[i];
}
return sum / n;
}
```
这个函数接受两个参数:一个整数数组score和数组的长度n。它通过循环遍历数组并将所有数字加起来,最后除以数组长度求得平均值。你可以像这样调用它:
```cpp
int main() {
int score[10] = {80, 90, 85, 70, 92, 88, 75, 95, 87, 82};
double avg = average(score, 10);
cout << "平均成绩是:" << avg << endl;
return 0;
}
```
输出结果为:
```
平均成绩是:84.4
```
希望这个函数可以帮助到你!
实验四的名称: 一维数组名做函数参数 有一个一维数组score,内放一个学生的六门课成绩,求该学生的总成绩。
好的,以下是将一维数组作为函数参数来计算学生总成绩的代码实现:
```c++
#include <iostream>
using namespace std;
int sum(int arr[], int len){
int total = 0;
for(int i = 0; i < len; i++){
total += arr[i];
}
return total;
}
int main(){
int score[6] = {90, 85, 92, 88, 95, 90};
int len = sizeof(score) / sizeof(score[0]);
int total = sum(score, len);
cout << "该学生的总成绩为:" << total << endl;
return 0;
}
```
在上面的代码中,我们定义了一个名为sum的函数,它以两个参数:一个一维数组arr和该数组的长度len作为输入参数。在函数体内,我们使用for循环遍历数组arr中的每一个元素,并将其累加到total变量中。最后,函数返回total的值,即为该学生的总成绩。
在主函数中,我们首先定义了一个一维数组score,并初始化其元素值。然后,我们计算出数组score的长度len,并调用sum函数,将数组score和其长度len作为参数传递给sum函数。最后,我们输出该学生的总成绩。
运行上面的代码,输出结果为:该学生的总成绩为:540。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)