我正在从书本上自己学习python并解决问题。在一个问题中,用户输入几年中一年中每月的降雨量。我需要找到每年的平均降雨量(总和(每月降雨量)/ numb_months),以及该时期内(例如两年)的平均降雨量。在下面的代码中,我可以得到每年的平均降雨量(I为了避免繁琐的输入,现在只用了3个月而不是12个月),但是我不知道在那个时期需要在哪里放置总蓄雨量的蓄雨量然后求平均。感谢您的帮助。
number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))
for year in range(years_in_period):
yearly_rain = 0
print('Year', year+1)
print('−−−−−−−−−−−−−−−−−')
for month in range(number_of_months):
print('Month', month+1, end='')
monthly_rain = float(input("Please enter rainfall for this month: \n"))
yearly_rain += monthly_rain
average_yearly_rainfall = yearly_rain / number_of_months
print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
print("Year total rain is", yearly_rain)
print()
答案 0 :(得分:0)
如果我了解您想要的内容(计算该时段内雨量的绝对平均值),那么就可以做到这一点:
number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))
total_rain = 0
for year in range(years_in_period):
yearly_rain = 0
print('Year', year+1)
print('−−−−−−−−−−−−−−−−−')
for month in range(number_of_months):
print('Month', month+1, end='')
monthly_rain = float(input("Please enter rainfall for this month: \n"))
yearly_rain += monthly_rain
total_rain += monthly_rain
average_yearly_rainfall = yearly_rain / number_of_months
print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
print("Year total rain is", yearly_rain)
print()
total_months = years_in_period * number_of_months
print("Absolute average of rain/month was", total_rain/total_months)
print("Absolute average of rain/year was", total_rain/years_in_period)