如果年份的输入值= 2,我如何让我的程序在前12个月显示第1年,然后在接下来的12个月显示第2年?
另外,我不知道我的计算出错了。根据我想要的输出,总降雨量应该是37,但我得到39。
#the following are the values for input:
#year 1 month 1 THROUGH year 1 month 11 = 1
#year 1 month 12 THROUGH year 2 month 12 = 2
def main():
#desired year = 2
years = int(input("Enter the number of years you want the rainfall calculator to determine: "))
calcRainFall(years)
def calcRainFall(yearsF):
months = 12
grandTotal = 0.0
for years_rain in range(yearsF):
total= 0.0
for month in range(months):
print('Enter the number of inches of rainfall for year 1 month', month + 1, end='')
rain = int(input(': '))
total += rain
grandTotal += total
#This is not giving me the total I need. output should be 37.
#rainTotal = rain + grandTotal
#print("The total amount of inches of rainfall for 2 year(s), is", rainTotal)
print("The total amount of inches of rainfall for 2 year(s), is", grandTotal)
main()
答案 0 :(得分:3)
在打印声明之前,您不需要为rainTotal再次添加降雨值。这是因为grandTotal每年都有降雨量。它已经两年加两次了。所以你所做的实际上是两次加雨的最后一次(在这种情况下为2) 制作你的打印声明并删除rainTotal -
print("The total amount of inches of rainfall for 2 year(s), is", grandTotal)
答案 1 :(得分:2)
我已经缩短了你的代码。希望这是一个完整而正确的计划:
def main():
years = int(input("Enter the number of years you want the rainfall calculator to determine: "))
calcRainFall(years)
def calcRainFall(yearsF):
months = 12 * yearsF # total number of months
grandTotal = 0.0 # inches of rain
for month in range(months):
# int(month / 12): rounds down to the nearest integer. Add 1 to start from year 1, not year 0.
# month % 12: finds the remainder when divided by 12. Add 1 to start from month 1, not month 0.
print('Enter the number of inches of rainfall for year', int(month / 12) + 1, 'month', month % 12 + 1, end='')
rain = int(input(': '))
grandTotal += rain
print("The total amount of inches of rainfall for", yearsF, "year(s), is", grandTotal)
main()
答案 2 :(得分:0)
rainTotal = rain + grandTotal
正在执行以下操作:2 + 37,因为您的最后一次降雨输入= 2且已经是总数或者总计= 37(每年的总输入数),因此 rainTotal = rain + grandTotal 是不需要
答案 3 :(得分:0)
您的代码备注:
如前所述,rainTotal是不必要的。
您可以尝试:
print 'Enter the number of inches of rainfall for year %d month %d' % (years_rain, month), end='')
这将填充第一个%d表示years_rain的值,第二个%d表示月份值作为for循环运行。
此技巧也可用于最终打印行,如下所示:
print("The total amount of inches of rainfall for %d year(s) % yearsF, is", grandTotal)