首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >平均雨量计算器

平均雨量计算器
EN

Stack Overflow用户
提问于 2012-07-14 07:09:56
回答 1查看 7K关注 0票数 2

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

代码语言:javascript
复制
# 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()

这是我在尝试测试代码时收到的新错误消息:

代码语言:javascript
复制
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行)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-14 07:50:13

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

代码语言:javascript
复制
average_inches = total / month

具体来说,

代码语言:javascript
复制
TypeError: unspupported operand type(s) for /: 'float' and 'str'

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

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

作为提示,我建议从做以下事情开始:

代码语言:javascript
复制
ALL_MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'):

然后将您的循环更改为:

代码语言:javascript
复制
for month in ALL_MONTHS:

这样你以后就可以再次引用ALL_MONTHS了。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11479485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档