如何添加计数器来跟踪while循环中的月份和年份?

2024-09-30 16:39:04 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图创建一个程序,我已经完成了程序的大部分,但我有一些计数器的问题。 -我需要添加一个数月或数年的计数器,用来跟踪成为百万富翁需要多长时间。 -我的月数计数器是正确的,但我很难算出年数计数器。你知道吗

以下是我目前的代码:

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}')

Tags: 程序input计数器floatyearprintenterbalance
2条回答

@vashïu踩踏者的答案有效。如果你想有一个完整的年数,你也可以在月是12的倍数时增加年的计数器。你知道吗

if month >= 12 and month % 12 == 0:
    year += 1

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

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}')

相关问题 更多 >