gpt4 book ai didi

Python求正数的平均值和负数的平均值

转载 作者:行者123 更新时间:2023-12-01 00:31:33 24 4
gpt4 key购买 nike

我正在为学校开发一个项目,无法弄清楚如何获取积极用户输入的平均值和消极用户输入的平均值并显示出来。我认为我走在正确的轨道上,并且我觉得我只缺少一两个步骤来完成该程序。这就是我必须开始的:

 print("(enter '0' to stop)")
cout_pos=0
count_neg=0
sum= 0.0
num=1
while num != 0:
num = int(input("enter value: "))
if num > 0:
sum = sum + num
count_pos +=1
if num < 0:
sum = sum + num
count_neg -=1


if sum == 0:
print("no values were entered")
else:
print('positive average: ' ,sum/(count_pos-1))
print('negative average: ' ,sum/(count_neg))

感谢您的帮助!

最佳答案

要使其正常工作,您需要为求和创建单独的变量,就像您对计数所做的那样,否则您将出现重叠:

print("(enter '0' to stop)")
count_pos=0
count_neg=0
sum_pos= 0
sum_neg= 0
num=1
while num != 0:
num = int(input("enter value: "))
if num > 0:
sum_pos = sum_pos + num
count_pos +=1
if num < 0:
sum_neg = sum_neg + num
count_neg -=1


if sum == 0:
print("no values were entered")
else:
print('positive average: ' ,sum_pos/(count_pos))
print('negative average: ' ,sum_neg/(count_neg))

输出:

enter value: 4
enter value: 4
enter value: 3
enter value: 3
enter value: -2
enter value: -4
enter value: 0
positive average: 3.5
negative average: 3.0

关于Python求正数的平均值和负数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com