繁体   English   中英

在Python中计算平均值?

[英]calculating average in python?

问题是:

询问用户她有几个孩子。 输入每个孩子的年龄(确保该值是介于0到100之间的数字)。 计算并输出用户孩子的平均年龄。

这是我到目前为止所拥有的:

child = int(input("How many children do you have?"))
count = 1
total = 0
if child > 100:
    print("Invalid!")
else:
    while count <= 11:
        n = int(input("Enter child #%s" %str(count)+ " age:"))
        count += 1
        total += n

    print("Average age:", total/child)

我无法设定孩子人数。 例如,当我输入3或7个孩子作为问题(您有几个孩子?)时,它仍然允许我输入11个孩子的年龄。 我知道我将其设置为<= 11,但是我不知道该怎么做? 另外,这是我尝试的while-loop ,我仍然需要使用for-loop 整体看来还不错吗?

你是在自问自答。 while count <= 11:则循环执行11次。

替换:将while count <= 11替换为while count <=child

如果我正确阅读了您的问题。 当它询问用户孩子的数量时,您将其存储在child变量中,然后使用它与孩子的最大年龄进行比较(100)。 这是不正确的。 从用户那里获得子变量输入后,应使用for循环以及range()函数,如下所示:

child = int(input("How many children do you have?"))
total =0
for num in range(child):
     n = int(input("Enter child age:"))
     if n > 100:
         print "error"
     total+=n

然后将总数与孩子平均。 不必定义num变量,因为Python会在for循环中为您完成此操作。 希望这可以帮助

更改

while count <= 11:

while count <= child:

您只循环11次,必须循环直到<=子时间。

让我通过提供正确的代码并向您解释其工作方式为您提供帮助:

child = int(input("How many children do you have?"))
count = 1
total = 0
if child > 100:
    print("Invalid!")
else:
    while count <= child:
        n = int(input("Enter child #%s" %str(count)+ " age:"))
        count += 1
        total += n

print("Average age:", total/child)

条件count <= child检查是否考虑了所有儿童。 您可以轻松地将其更改为for循环:

child = int(input("How many children do you have?"))
total = 0
if child > 100:
    print("Invalid!")
else:
    for count in range(child): # This start counting from 0
        n = int(input("Enter child #%s" %str(count)+ " age:"))
        total += n

print("Average age:", total/child)

实际上,此循环自身会重复numChildren次,达到我们想要的次数。 有关range一些证明,请检查此链接。

另外,由于您最有可能希望为child提供正确的输入,因此您可以编写以下代码来强制用户输入正确的输入:

child = int(input("How many children do you have?"))
count = 1
total = 0
while child > 100:
    print("Invalid!")
    child = int(input("How many children do you have?"))

while count <= child:
    n = int(input("Enter child #%s" %str(count)+ " age:"))
    count += 1
    total += n

print("Average age:", total/child

使用child而不是11

要使用for循环,您可以摆脱count计数器,只需要for i in range(child):做。

奇怪的是,没有提供的答案会检查给定的孩子数是否大于零。 没有人认为平均年龄在大多数情况下不是整数。

您必须检查child > 0并计算最终结果为float

child = int(input("How many children do you have?"))
count = 1
total = 0
if child <= 0 or child > 100:
    print("Invalid!")
else:
    while count <= child:
        n = int(input("Enter child #%s" %str(count)+ " age:"))
        count += 1
        total += n

    print("Average age:", float(total)/float(child))

暂无
暂无

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

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