Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 月平均降雨量计划的逻辑帮助_Python - Fatal编程技术网

Python 月平均降雨量计划的逻辑帮助

Python 月平均降雨量计划的逻辑帮助,python,Python,我正试图编写一个程序,使用嵌套循环来收集数据并计算多年的平均降雨量。程序应询问年数。外部循环将每年迭代一次。内部循环将迭代12次,每月一次。内部循环的每次迭代都会询问用户当月降雨量的英寸数 在所有迭代之后,程序应显示整个期间的月数、总降雨量和每月平均降雨量 years = int(input('How many years do you want to track? ')) months = 12 for years_rain in range(years): total= 0.0 pr

我正试图编写一个程序,使用嵌套循环来收集数据并计算多年的平均降雨量。程序应询问年数。外部循环将每年迭代一次。内部循环将迭代12次,每月一次。内部循环的每次迭代都会询问用户当月降雨量的英寸数

在所有迭代之后,程序应显示整个期间的月数、总降雨量和每月平均降雨量

years = int(input('How many years do you want to track? '))

months = 12

for years_rain in range(years):

total= 0.0

print('\nYear number', years_rain + 1)
print('------------------------------')
for month in range(months):
    print('How many inches for month ', month + 1, end='')
    rain = int(input(' did it rain? '))
    total += rain


number_months = years * months
average = total / number_months

print('The total inches of rain was ', format(total, '.2f'),'.')  
print('The number of months measured was', number_months)
print('The average rainfall was', format(average, '.2f'), 'inches')
此程序的逻辑已关闭。它是基于去年总降雨量的平均降雨量,而不是所有年份的总降雨量


这个程序的逻辑哪里出错了?

如果代码格式正确,您会注意到:

for years_rain in range(years):

    total= 0.0

    print('\nYear number', years_rain + 1)
    ...
这会将年度循环的每次迭代的总数重置为零。改为:

total = 0.0

for years_rain in range(years):  

    print('\nYear number', years_rain + 1)
    ...
您的总值正在重置,因此您需要一种方法来跟踪总计。有一种方法可以做到这一点:

years = int(input('How many years do you want to track? '))

months = 12

grandTotal = 0.0 // will store TOTAL rainfall

for years_rain in range(years):

    total= 0.0

    print('\nYear number', years_rain + 1)
    print('------------------------------')
    for month in range(months):
        print('How many inches for month ', month + 1, end='')
        rain = int(input(' did it rain? '))
        total += rain

    grandTotal += total // add total to the grandTotal

number_months = years * months
average = grandTotal / number_months

print('The total inches of rain was ', format(average, '.2f'),'.')  
print('The number of months measured was', number_months)
print('The average rainfall was', format(average, '.2f'), 'inches')

你能检查一下代码的格式吗?似乎没有任何牵连,也不确定内部循环是否终止。谢谢大家的帮助!所以这是整个场的位置。我永远也不会明白。非常感谢。