2012-07-13 115 views
2

這是更新的程序我至今寫:平均降雨量計算器

# This program averages rainfall per month. It asks the user for the number 
# of years. It will then display the number of months, the total inches of 
# rainfaill, and the average rainfall per month for the entire period. 

# Get the number of years. 

total_years = int(input('Enter the amount of years: ')) 

# Get the amount of rainfall for each month of each year. 

for years in range(total_years): 
    # Initialize the accumulator. 
    total = 0.0 
    print('Year', years + 1) 
    print('----------------') 
    for month in ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'): 
     inches = float(input(month)) 
     total += inches 

total_inches = total 

total_month = total_years * 12 

average_inches = total/total_month 



     # Display the average. 
print('The total number of months is: ', total_month) 
print('The total inches of rainfall is: ', total_inches) 
print('The average rainfall per month for the entire period is: ', average_inches) 

print() 

這是試圖測試代碼時,我得到了新的錯誤消息:在

Traceback (most recent call last): File 
"C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 
5/Average Rainfall maybe.py", line 23, in <module> 
average_inches = total/month 
TypeError: unspupported operand type(s) for /: 'float' and 'str' 

任何想法如何修復/改進此代碼?

現在,我需要解決的是我的計算。我認爲他們錯了(23-27行)。

+1

不提供帶有兩個參數的輸入,刪除',月份'並在傳入的字符串中添加有獎月份 – rlemon 2012-07-13 23:13:46

+1

'input('輸入在月份%s'%月份中測量的英寸數量'' – 2012-07-13 23:25:34

+1

請勿使用輸入。使用raw_input。 – 2012-07-13 23:28:28

回答

4

發生錯誤的錯誤消息的引用:

average_inches = total/month 

具體地說,

TypeError: unspupported operand type(s) for /: 'float' and 'str' 

..是說,它不能除以一個字符串(month)的浮子(total)。

month要由分(它只是包含「一」或任何字符串)..你想要的number of months

以提示劃分完全錯誤的事情,我做建議開始:

ALL_MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'): 

然後你的循環更改爲:

for month in ALL_MONTHS: 

這樣,您可以稍後查閱ALL_MONTHS再次...

+1

我只是做了兩次。由於錯誤消息已被編輯,我的答案不再解決問題:P,無論如何+1。 – 2012-07-13 23:56:14