我遇到嵌套循环问题。在一年中,我希望我的循环将每年的每个数字加起来。当年份结束而不是添加去年的数字并将其添加到新的一年时,我希望它再次从0开始。
最后,它应该向我展示每年的总数,并给出我所有年份的平均值。
以下是我的样本,如果有人可以帮我完成它:
total_rain = 0
month = 12
y = 0
rain = 0
month_rain = 0
years = int(input("How many years: "))
for y in range(years):
y += 1
print()
print("In the year", y,"There will be:")
for m in range(month):
rain = float(input('How many inch of rainfall have fallen: '))
total_rain += rain
print(month_rain)
main()
每次循环结束时,它都会添加上一年的数字。我希望新循环再次从0开始并加上数字。
答案 0 :(得分:0)
total_rain = 0
month = 12
rain = 0
years = int(input("How many years: "))
for y in range(years):
month_rain = 0
print()
print("In the year", y,"There will be:")
for m in range(month):
rain = float(input('How many inch of rainfall have fallen: '))
month_rain += rain
total_rain += month_rain
print("year %s: %s" % (y, month_rain) )
print("total rain: %s" % (total_rain/years))
答案 1 :(得分:0)
total_rain = []
months = 12
years = int(input("How many years: "))
for y in range(1, years+1):
print("In the year", y,"There will be:")
annual_rain = []
for m in range(1,13):
rain = float(input('How many inch of rainfall have fallen in month %s: ' %m))
annual_rain.append(rain)
total_rain.append(annual_rain)
for y,year in enumerate(total_rain, 1):
print("Total rain in year %s: %s. Average monthly rain: %s" %(y, sum(year), sum(year)/len(year)))
答案 2 :(得分:0)
for y in range(years):
y += 1
for m in range(month):
rain = float(input('How many inch of rainfall have fallen: '))
total_rain += rain
print("In the year", y,"There will be:", total_rain," inches of rain")
#reset variable
total_rain = 0
首先,我更正了“total_rain + = rain”的缩进,因为你将它嵌套在第二个for循环之外,因此它实际上不会添加你每次输入的降雨量。
然后我所做的就是将总降雨设置为0以重置它。
它就像一个魅力,与你自己的代码非常相似。