total_months = 0
rainfall_inches = 0
years = int(input("How many years of data do you wish to collect? "))
for currentYear in range(1, years + 1):
for currentMonth in range(1, 13):
monthly_rainfall = float(input("Enter the inches of rainfall for month "
+ format(currentMonth, "d") + ", year " + format(currentYear,"d") +
": "))
rainfall_inches += monthly_rainfall
total_months += 1
avg_rainfall = rainfall_inches / total_months
print("Number of months: " + format(total_months, "d"), "Total inches of `
rainfall: " + format(rainfall_inches, ".2f"), "Average rainfall: " + `
format(avg_rainfall, ".2f"), sep="\n")
答案 0 :(得分:1)
一种方法是添加annual_avgs列表并在外部for循环中更新它,并从该列表中查找总平均值,而不是使用total_months。例如:
yearly_avgs = [] # initialize list for yearly averages
total_months = 0
rainfall_inches = 0
years = int(input("How many years of data do you wish to collect? "))
for currentYear in range(1, years + 1):
for currentMonth in range(1, 13):
monthly_rainfall = float(input("Enter the inches of rainfall for month "
+ \
format(currentMonth, "d") + ", year " + format(currentYear,"d") +
": "))
rainfall_inches += monthly_rainfall
total_months += 1
yearly_avgs += rainfall_inches # append average for currentYear
rainfall_inches = 0 # reset rainfall_inches
avg_rainfall = sum(yearly_avgs)/years # get average over years
print("Number of months: " + format(total_months, "d"), "Total inches of `
rainfall: " + format(rainfall_inches, ".2f"), "Average rainfall: " + `
format(avg_rainfall, ".2f"), sep="\n")
它仍然有点笨拙,但我认为它完成了工作。