要求通过全局变量将正数和负数的平均值传递给调用程序
时间: 2023-06-13 12:07:33 浏览: 56
好的,你可以使用以下代码来实现:
```python
# 初始化全局变量
positive_sum = 0
positive_count = 0
negative_sum = 0
negative_count = 0
# 计算平均值
def calculate_average(num):
global positive_sum, positive_count, negative_sum, negative_count
if num >= 0:
positive_sum += num
positive_count += 1
else:
negative_sum += num
negative_count += 1
# 获取平均值
def get_average():
global positive_sum, positive_count, negative_sum, negative_count
positive_average = 0 if positive_count == 0 else positive_sum / positive_count
negative_average = 0 if negative_count == 0 else negative_sum / negative_count
return positive_average, negative_average
```
在这个代码中,我们定义了四个全局变量 `positive_sum`,`positive_count`,`negative_sum` 和 `negative_count` 来分别计算正数和负数的总和和数量。
`calculate_average()` 函数接受一个数字作为参数,并根据该数字是正数还是负数将其添加到相应的总和和计数器中。
最后,`get_average()` 函数通过除以相应的总数计算出正数和负数的平均值,并将其作为元组返回给调用程序。
你可以在需要计算平均值的地方调用 `calculate_average()` 函数,然后在需要获取平均值的地方调用 `get_average()` 函数来获取结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)