【发布时间】:2019-03-09 07:59:51
【问题描述】:
谁能告诉我为什么当我在这段代码中输入 1、2、3 和 4 时,我的输出是 6、2、3.00?我认为每次我的 while 循环评估为 true 时,它都会将计数加一,但输出没有意义。它总共取了 3 个数字,但计数只有 2 个?我可能只是忽略了一些东西,所以多一双眼睛会很棒。
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
【问题讨论】:
-
你调用
inputPositiveInteger(),检查它是否等于-1,否则忽略它的值,然后另一个调用inputPositiveInteger(),并将它添加到你的总计和计数(即使是 -1)。
标签: python-3.x function while-loop increment