gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:01:41 25 4
gpt4 key购买 nike

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

这是迄今为止我的代码:

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

最佳答案

经过讨论,最终结果是:

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

关于python - 如何添加一个计数器来跟踪 while 循环中的月份和年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com