【问题标题】:Accumulator for outer nested loop Python外部嵌套循环 Python 的累加器
【发布时间】:2018-11-14 18:15:33
【问题描述】:

我正在从一本书中自学python并解决问题。在一个问题中,用户输入跨年的一年中每个月的降雨量。我需要找到每年的平均降雨量(sum(monthly rain)/numb_months,以及那个时期的平均降雨量,例如两年。在下面的代码中,我可以得到每年的平均值(我只用了 3 个月而不是 12 个月,以避免现在繁琐的输入),但我不知道我需要在哪里放置那个时期的总降雨量的蓄能器,然后平均它。感谢您的帮助。

number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))

for year in range(years_in_period):
    yearly_rain = 0
    print('Year', year+1) 
    print('−−−−−−−−−−−−−−−−−')
    for month in range(number_of_months):
        print('Month', month+1, end='')
        monthly_rain = float(input("Please enter rainfall for this month: \n"))
        yearly_rain += monthly_rain
        average_yearly_rainfall = yearly_rain / number_of_months
    print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
    print("Year total rain is", yearly_rain)
    print()

【问题讨论】:

    标签: python loops nested accumulator


    【解决方案1】:

    如果我明白你想要什么(计算期间降雨量的绝对平均值),这应该可以解决问题:

    number_of_months = 3
    years_in_period = int(input("Please enter the number of years in the period. \n"))
    
    total_rain = 0
    
    for year in range(years_in_period):
        yearly_rain = 0
        print('Year', year+1) 
        print('−−−−−−−−−−−−−−−−−')
    
        for month in range(number_of_months):
            print('Month', month+1, end='')
            monthly_rain = float(input("Please enter rainfall for this month: \n"))
    
            yearly_rain += monthly_rain
    
            total_rain += monthly_rain
    
            average_yearly_rainfall = yearly_rain / number_of_months
    
        print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
        print("Year total rain is", yearly_rain)
        print()
    
    
    total_months = years_in_period * number_of_months
    print("Absolute average of rain/month was", total_rain/total_months)
    print("Absolute average of rain/year was", total_rain/years_in_period)
    

    【讨论】:

    • 这就是我想要的!非常感谢 Pedro Martins 的快速帮助!
    • 没问题!如果您需要其他东西,请告诉我;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多