繁体   English   中英

Python :(计算正数和负数并计算数字的平均值)

[英]Python: (Count positive and negative numbers and compute the average of numbers)

问题陈述:编写一个程序,读取未指定数量的整数,确定已读取多少个正值和负值,并计算输入值的总和和平均值(不计零)。 您的程序以输入0结尾。将平均值显示为浮点数。

输出示例(忽略项目符号,不知道如何将文本格式化为控制台输出):

  • 输入一个整数,如果它是0:1,则输入结束
  • 输入一个整数,如果输入为0,则输入结束:2
  • 输入一个整数,如果为0,则输入结束:-1
  • 输入一个整数,如果输入为0,则输入结束:3
  • 输入一个整数,如果它是0:0,则输入结束
  • 您没有输入任何数字
  • 正数是3
  • 负数为1
  • 总数是5
  • 平均值是1.25

尝试的解决方案:

def main():
    i = int( input ("Enter an interger, the input ends if it is 0: "))
    count_pos = 0
    count_neg = 0
    total = 0
    if (i != 0):
        while (i != 0):
            if (i > 0):
                count_pos += 1
            elif (i < 0):
                count_neg += 1
            total += i
            i = int( input ("Enter an interger, the input ends if it is 0: "))
            count = count_pos + count_neg
            average = total / count

        print ("The number of positives is", count_pos)
        print ("The number of negatives is", count_neg)
        print ("The total is", total)
        print ("The average is", float(average))
    else:
        print ("You didn't enter any number.")

main()

您不需要此行(这就是发生错误的原因):

main(i)

要持续获取用户输入,请使用无限循环,然后测试打破循环的条件。

while (true):
    i = input("Enter an integer (0 to stop): ")
    if(i == 0)
        break
    sum1 += i
    if (i > 0):
      count_pos += 1
    elif (i < 0):
      count_neg += 1

然后计算并返回平均值。

您正在使用参数“ i”调用主函数,该参数不存在。 您不能使用在该函数之外的函数中声明的变量

检出: Python作用域

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM