如何添加一个计数器来跟踪一个 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}')


拉丁的传说
浏览 238回答 2
2回答

慕雪6442864

经过这里的讨论是最终结果:balance = float(input("Enter initial amount: "))monthlyContribution = float(input("Enter monthly contribution: "))interestRate = float(input("Enter annual interest rate: "))month = 0interest = interestRate/100while balance < 1000000 :&nbsp; &nbsp; month = month + 1&nbsp; &nbsp; balance +=&nbsp; monthlyContribution + (balance + monthlyContribution) * interest/12&nbsp; &nbsp; if not month % 12:&nbsp; &nbsp; &nbsp; &nbsp; year = month//12&nbsp; &nbsp; &nbsp; &nbsp; rem = month % 12&nbsp; &nbsp; &nbsp; &nbsp; print(f'Current Balance: ${balance:,.2f} after {month} or {year} years' +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f'and {rem} months')year = month//12rem = month % 12print(f'\nCongratulations, you will be a millionaire in {month} months' +&nbsp; &nbsp; &nbsp; f' or {year} years and {rem} months' +&nbsp; &nbsp; &nbsp; f'\nCurrent Balance: ${balance:,.2f}')

慕姐8265434

如果您想拥有整数年,您还可以在月份是 12 的倍数时增加年份的计数器。if month >= 12 and month % 12 == 0:&nbsp; &nbsp; year += 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python