Python找到正数的平均值而发现负数的平均值

时间:2019-09-27 18:06:38

标签: python

我正在为一个学校项目工作,无法弄清楚如何获得正用户输入的平均值和负用户输入的平均值,并将其显示出来。我认为我走在正确的轨道上,我觉得我只差一两个步骤就可以完成程序。这是我必须开始的:

 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))

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这是另一个版本:

def average(lst):
    """ Count average from the list of numbers """
    return sum(lst) / len(lst)


positive = []  # list of positive numbers
negative = []  # list of negative numbers
num = None

print("(enter '0' to stop)")
while True:
    try:  # try to enter float values
        num = float(input('enter value: '))
    except ValueError:  # non-number was entered
        print('please, enter only numbers')
        continue  # start from beginning of while loop

    if num > 0:  # if positive, append number to positive list
        positive.append(num)
    elif num < 0:  # if negative, append number to negative list
        negative.append(num)
    else:  # if zero, exit from the while loop
        break

# Use f-strings to print for Python 3.7 and higher
if len(positive):
    print(f'positive average: {average(positive)}')
if len(negative):
    print(f'negative average: {average(negative)}')
if len(positive) == 0 and len(negative) == 0:
    print('no values were entered')

输出为:

(enter '0' to stop)
enter value: 1.5
enter value: 3.7
enter value: a
please, enter only numbers
enter value: 4.6
enter value: -2.78
enter value: -9.99
enter value: 0a
please, enter only numbers
enter value: 0.0
positive average: 3.266666666666667
negative average: -6.385