2014-06-13 74 views
0

我正在嘗試編寫一個程序,該程序使用嵌套循環來收集數據並計算一段時間內的平均降雨量。該程序應該詢問年數。外循環將每年迭代一次。內循環將迭代十二次,每月一次。內循環的每次迭代都會詢問用戶該月的降雨數量。每月平均雨量計劃的邏輯幫助

經過所有迭代後,程序應顯示月份數,降雨總英寸數和整個週期的每月平均降雨量。

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

謝謝大家的幫助! – user3030048

回答

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) 
    ... 
+0

所以這是「總」字段的位置。我從來沒有得到過。謝謝! – user3030048

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')