cyuyan编写函数,求一组数中的最大值、最小值和平均值。其中用全局变量max存放最大值,min存放最小值,函数返回平均值。
时间: 2023-12-14 20:37:17 浏览: 90
以下是一个示例代码:
```python
max = 0 # 全局变量,用于存放最大值
min = 0 # 全局变量,用于存放最小值
def max_min_avg(nums):
global max, min # 声明使用全局变量
sum = 0 # 用于计算总和
for num in nums:
if num > max:
max = num
if num < min:
min = num
sum += num
return sum / len(nums) # 计算平均值并返回
# 示例用法
nums = [1, 2, 3, 4, 5]
avg = max_min_avg(nums)
print("最大值:", max)
print("最小值:", min)
print("平均值:", avg)
```
注意:全局变量的使用需要在函数中进行声明,否则 Python 会将其视为局部变量。另外,如果输入的列表为空,上述代码会报除以零的错误。可以在函数开头添加如下代码来避免这个问题:
```python
if len(nums) == 0:
return 0
```
相关问题
cyuyan编写函数,求一组数中的最大值、最小值和平均值。其中用全局变量max存放最大值,min存放最小值,函数返回平均值。
好的,以下是cyuyan编写的函数,可以实现求一组数中的最大值、最小值和平均值,并且使用了全局变量max和min存放最大值和最小值,函数返回平均值。
```python
max = 0
min = 0
def max_min_avg(num_list):
global max, min
sum = 0
n = len(num_list)
# 计算平均值
for num in num_list:
sum += num
avg = sum / n
# 计算最大值和最小值
max = num_list[0]
min = num_list[0]
for num in num_list:
if num > max:
max = num
if num < min:
min = num
return avg
```
使用方法示例:
```python
num_list = [1, 3, 5, 7, 9]
avg = max_min_avg(num_list)
print("最大值:", max)
print("最小值:", min)
print("平均值:", avg)
```
输出结果:
```
最大值: 9
最小值: 1
平均值: 5.0
```
7-2 编写函数,完成一组学生C语言成绩的值的运算 cyuyan1
好的,以下是一个实现该功能的 Python 函数示例:
```python
def calculate_scores(scores):
"""
计算一组学生的 C 语言成绩的值的运算
:param scores: 学生的成绩列表,每个元素表示一个学生的成绩
:return: 返回一个字典,包括总分、平均分、最高分和最低分
"""
total_score = sum(scores) # 总分
avg_score = total_score / len(scores) # 平均分
max_score = max(scores) # 最高分
min_score = min(scores) # 最低分
result = {
"total_score": total_score,
"avg_score": avg_score,
"max_score": max_score,
"min_score": min_score
}
return result
```
使用方法:
```python
scores = [70, 80, 90, 85, 75]
result = calculate_scores(scores)
print(result)
```
输出结果:
```
{'total_score': 400, 'avg_score': 80.0, 'max_score': 90, 'min_score': 70}
```
阅读全文
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)