我正在尝试编写一个程序,该程序使用嵌套循环来收集数据并计算一段时间内的平均降雨量。该计划应询问年数。外循环将每年迭代一次。内循环将迭代十二次,每个月一次。内循环的每次迭代将询问用户该月的降雨量英寸数。
在所有迭代之后,程序应显示整月的nubmer,降雨总英寸和每月平均降雨量。
years = int(input('How many years do you want to track? '))
months = 12
for years_rain in range(years):
total= 0.0
print('\nYear number', years_rain + 1)
print('------------------------------')
for month in range(months):
print('How many inches for month ', month + 1, end='')
rain = int(input(' did it rain? '))
total += rain
number_months = years * months
average = total / number_months
print('The total inches of rain was ', format(total, '.2f'),'.')
print('The number of months measured was', number_months)
print('The average rainfall was', format(average, '.2f'), 'inches')
此程序的逻辑已关闭。它的平均降雨量是去年的总降雨量,而不是所有年份的降雨量。降雨总量。
我在这个程序的逻辑中出错了什么?
答案 0 :(得分:0)
使用格式正确的代码,您会注意到:
for years_rain in range(years):
total= 0.0
print('\nYear number', years_rain + 1)
...
将total
重置,使每年循环的每次迭代归零。将其改为:
total = 0.0
for years_rain in range(years):
print('\nYear number', years_rain + 1)
...
答案 1 :(得分:0)
您的total
值正在重置,因此您需要一种方法来跟踪grandTotal
。这是实现此目的的一种方法:
years = int(input('How many years do you want to track? '))
months = 12
grandTotal = 0.0 // will store TOTAL rainfall
for years_rain in range(years):
total= 0.0
print('\nYear number', years_rain + 1)
print('------------------------------')
for month in range(months):
print('How many inches for month ', month + 1, end='')
rain = int(input(' did it rain? '))
total += rain
grandTotal += total // add total to the grandTotal
number_months = years * months
average = grandTotal / number_months
print('The total inches of rain was ', format(average, '.2f'),'.')
print('The number of months measured was', number_months)
print('The average rainfall was', format(average, '.2f'), 'inches')