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行目)。

4

1 に答える 1

4

エラーメッセージは、エラーが発生した場所を示しています。

average_inches = total / month

具体的には、

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

..フロート(total)を文字列(month)で除算できないと言っています。

month除算するのは完全に間違っています(「1月」などを含む文字列です)。月数で除算したい

ヒントとして、次のことから始めることをお勧めします。

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

次に、ループを次のように変更します。

for month in ALL_MONTHS:

そうすれば、ALL_MONTHS後でもう一度参照できます...

于 2012-07-13T23:50:13.323 に答える