【问题标题】:Average Rainfall Calculator平均降雨量计算器
【发布时间】:2012-09-17 03:15:02
【问题描述】:

这是我目前写的更新程序:

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

【问题讨论】:

  • 不要提供带有两个参数的输入,删除, month 并在传递的字符串中添加迭代月份
  • input('Enter the inches measured in month %s'% month)
  • 不要使用输入法。使用 raw_input。
  • @ColinDunklau 仅在 Python 2 中。在 Python 3(这似乎是)中,您应该使用 input
  • @Liquid_Fire 很高兴知道,谢谢!

标签: python average


【解决方案1】:

错误消息引用了发生错误的位置:

average_inches = total / month

具体来说,

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

..表示它不能将浮点数 (total) 除以字符串 (month)。

month 是完全错误的除以(它只是一个包含“January”或其他内容的字符串)。你想除以number of months

作为提示,我建议先这样做:

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

然后将循环更改为:

for month in ALL_MONTHS:

这样你以后可以再次参考ALL_MONTHS...

【讨论】:

  • 我刚刚拍了两遍。由于错误消息已被编辑,我的回答不再解决问题:P,无论如何+1。
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多