用自定义函数的形式编写程序实现求10名学生1门功课的平均分
时间: 2023-11-28 09:47:45 浏览: 117
以下是用 Python 编写的求10名学生1门功课平均分的程序:
```python
def calculate_average(scores):
total = sum(scores)
return total / len(scores)
# 输入每个学生的分数
scores = []
for i in range(10):
score = float(input("请输入第 %d 名学生的分数:" % (i+1)))
scores.append(score)
# 计算平均分并输出结果
average_score = calculate_average(scores)
print("10名学生的平均分为:%.2f" % average_score)
```
运行程序后,会依次提示用户输入每个学生的分数,最后输出平均分。其中,`calculate_average` 函数用于计算平均分,输入参数为一个列表,返回值为平均分。`sum` 函数用于求和,`len` 函数用于获取列表长度。`%.2f` 表示保留两位小数。
相关问题
用自定义函数形式编程实现求10名学生1门课程成绩的平均分
好的,下面是代码实现:
```
def average_score(scores):
total = sum(scores)
return total / len(scores)
# 假设10名学生的分数分别为:80, 90, 70, 85, 91, 78, 84, 92, 87, 76
scores = [80, 90, 70, 85, 91, 78, 84, 92, 87, 76]
avg_score = average_score(scores)
print("10名学生1门课程成绩的平均分为: {:.2f}".format(avg_score))
```
输出结果为:
```
10名学生1门课程成绩的平均分为: 83.30
```
请用自定义函数的形式编程实现求10名学生1门课程成绩的平均分利用C语言
以下是用C语言实现求10名学生1门课程成绩的平均分的代码:
```c
#include <stdio.h>
// 自定义函数,输入一个数组和数组长度,返回平均值
float avg(float arr[], int len)
{
float sum = 0;
int i;
for (i = 0; i < len; i++) {
sum += arr[i];
}
return sum / len;
}
int main()
{
float scores[10];
int i;
for (i = 0; i < 10; i++) {
printf("请输入第%d名学生的成绩:", i + 1);
scanf("%f", &scores[i]);
}
float average = avg(scores, 10);
printf("10名学生的平均成绩为%.2f\n", average);
return 0;
}
```
该程序首先定义了一个自定义函数`avg`,输入一个数组和数组长度,返回平均值。然后在`main`函数中定义了一个长度为10的数组`scores`,并通过循环输入每个学生的成绩。最后调用`avg`函数计算平均分,并输出结果。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)