首页 > 解决方案 > 如何在一个while循环中添加一个计数器来跟踪月份和年份?

问题描述

所以我正在尝试创建一个程序,并且我的程序大部分都完成了,但是我在使用计数器时遇到了一些问题。-我需要添加一个数月和数年的计数器来跟踪成为百万富翁需要多长时间。- 我的月份计数器是正确的,但我在试图找出年份计数器时遇到了麻烦。

到目前为止,这是我的代码:

balance = float(input("Enter initial amount: "))
monthlyContribution = float(input("Enter monthly contribution: "))
interestRate = float(input("Enter annual interest rate: "))
month = 0
year = 0

while balance < 1000000 :
   month = month + 1
   year = year + 1
   interest = interestRate/100
   balance = balance + monthlyContribution + (balance + monthlyContribution) * interest/12
   print(f'Current Balance: ${balance:,.2f}', (f'after {month} months'), (f' or {year} years'))

print(f'Congratulations, you will be a millionaire in {month} months: ${balance:,.2f}')

标签: pythonpython-3.xpython-3.6

解决方案


经过讨论,这里是最终结果:

balance = float(input("Enter initial amount: "))
monthlyContribution = float(input("Enter monthly contribution: "))
interestRate = float(input("Enter annual interest rate: "))
month = 0
interest = interestRate/100

while balance < 1000000 :
    month = month + 1
    balance +=  monthlyContribution + (balance + monthlyContribution) * interest/12
    if not month % 12:
        year = month//12
        rem = month % 12
        print(f'Current Balance: ${balance:,.2f} after {month} or {year} years' +
              f'and {rem} months')

year = month//12
rem = month % 12

print(f'\nCongratulations, you will be a millionaire in {month} months' +
      f' or {year} years and {rem} months' +
      f'\nCurrent Balance: ${balance:,.2f}')

推荐阅读