计算平均值不起作用

时间:2015-03-17 17:58:25

标签: python math

代码产生:你给了我以下数字:1 2 3。计算平均值时,它等于0。我需要的答案是2。

def get_numbers():
    print "Enter any numbers, when you are finished press q   "
    my_list = []
    while True:
        number = raw_input()
        if number != "q":
            num = int(number)
            my_list.append(num)
        else:
            return my_list


def add():
    the_list = get_numbers()
    total = 0
    for i in the_list:
        total = total*i
        total = total/len(the_list)
    print "You gave me the following numbers:",
    for x in the_list:
        y = str(x)
        print y,
    print ".", "When the mean is calculated it equals", total, "."

add()

1 个答案:

答案 0 :(得分:2)

你遇到的核心问题是你应该这样做:

total = 0
for i in the_list:
    total = total+i
total = float(total)/len(the_list)

你需要添加数字而不是将它们相乘,然后在迭代结束时分成列表的长度。

您的代码还存在各种其他问题:

  • 名称add实际上并没有说明它的作用
  • 您可能还应该将I / O(查询用户,打印结果)与计算分开(计算平均值)。

此版本解决了这些问题:

def get_numbers():
    print "Enter any numbers, when you are finished press q   "
    my_list = []
    while True:
        number = raw_input()
        if number != "q":
            num = int(number)
            my_list.append(num)
        else:
            return my_list

def mean(l):
    total = 0
    for i in l:
        total = total + i
    r = float(total)/len(l)
    return r 

def main():
    the_list = get_numbers()
    print "You gave me the following numbers:",
    for x in the_list:
        y = str(x)
        print y,
    print ".", "When the mean is calculated it equals", mean(the_list), "."


main()