python新手。想知道是否有人可以检查我的代码是否解决了问题

时间:2019-02-02 07:48:24

标签: python average

编写一个程序,该程序使用嵌套循环收集数据并计算几年内的平均降雨量。该程序应首先询问年数。外部循环每年重复一次。内循环将迭代十二次,每月一次。内循环的每次迭代都会向用户询问该月的降雨英寸数。所有迭代后,程序应该显示月的雨量的总英寸的数量,和每月的平均降雨量在整个期间。

input_years=int(input('Enter number of years:'))
for years in range(input_years+1):
    total = 0.0
    for month in range(13):
        input_month=int(input('Enter the amount of rainfall for that month:'))
        total=+input_month
    average=total/month
    print("This is the number of months:",input_month )
    print("This is the total number of rainfall",total,"inches")
    print("This is the average rainfall permonth",format(average,".2f"))

4 个答案:

答案 0 :(得分:0)

您的代码在一年内循环太多次。它应该循环12次却循环13次。

使用Python 2.代码输出这样当格式化不正确:

('This is the number of months:', 13)
('This is the total number of rainfall', 13, 'inches')
('This is the average rainfall permonth', '1.00')

要解决这个问题,使用加变量,而不是使用逗号之间登录。当你这样做,你也将需要通过你的变量作为字符串到打印命令。

如果您使用Python 3中,该溶液将是所使用的()与打印除去。的信用为@SimonF的变化。

从用户那里接收降雨时,显示单位也可能是一个不错的功能。

希望这会有所帮助!

答案 1 :(得分:0)

最好自己尝试一下,但是我想在第二行指出这一点

for years in range(input_years+1):

您不需要添加“ +1”,因为它会在包括0在内的范围内进行迭代,请尝试以下操作:

for x in range(5):
    print("Hello World!")

它将打印5次“ Hello World”。

第4行也有同样的问题

for month in range(13):

答案 2 :(得分:0)

您的代码实际上有两个问题,一个是您在for month in range(13):中迭代了一个额外的时间,因为范围从0开始。另一个问题是您在total=+input_month的for循环中,因此只需将total设置为等于上个月的条目。应该是total += input_month

答案 3 :(得分:0)

您的代码存在的问题:

  1. For循环的每个迭代都太多了
  2. 要求您在整个期间而不是每年进行计算
  3. 您正在混淆变量,例如input_month不是月份数
  4. 您未将总数total=+input_month增加为total+=input_month

建议:

  1. 修复循环
  2. 整个期间总计,而不是每年
  3. 仅获取输入并增加循环中的总数
  4. 在两个循环之外进行计算
  5. 使用期限= 12 * input_years,平均值=总计/期间