Nested Loops 计算输出不正确,但程序运行

Nested Loops calculation output is incorrect, but program runs

如果年的输入值 = 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()

在打印语句之前,不需要再为rainTotal加上rain值。这是因为 grandTotal 计算了每年的降雨量。并且已经在两年内添加了两次。所以你所做的实际上是将 rain 的最后一个值加两次(在本例中为 2) 使你的打印语句这样并删除 rainTotal -

print("The total amount of inches of rainfall for 2 year(s), is", grandTotal)
rainTotal = rain + grandTotal

is performing following: 2 + 37 because you have last rain input = 2 and already total or grandTotal is = 37 (total input for each year) so rainTotal = rain + grandTotal is not needed

我稍微缩短了您的代码。希望这是一个完整且正确的程序:

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()

代码注释:

如前所述,不需要 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)