python - 如何在一个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}')
解决方案
经过讨论,这里是最终结果:
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}')
推荐阅读
- reporting-services - SSRS - 根据计算字段计算百分比
- pointers - 在结构字段中使用指针的区别
- javascript - 修改Chart.JS中散点图的信息框
- ios - 如何从 Google Translate Api 或云翻译 api 下载语言包以供离线使用?
- laravel-backpack - 为laravel 6安装背包时出错,elfinder有问题
- python - Django 日志记录错误:未创建日志文件
- c# - 如何设置两个连接字符串 MySqlCommand 对象参数?
- postgresql - 在 postgresql 中查询 now() 时出错
- pylint - Pylint 使用 fstring 在线提高日志记录格式插值
- sql-server - 如何真正撤消错误选择的索引创建?