为什么这段计算投资翻倍时长的Python代码中break语句不生效?
问题根因
你代码中的判断逻辑存在本质错误:当前balance是动态更新的,你用2*balance作为对比基准时,这个基准会随着balance上涨同步上涨,相当于你要追一个永远比你快一倍的目标,永远不可能满足相等的条件,自然无法跳出循环。同时复利计算下余额只会无限接近动态阈值不会精确相等,就算逻辑成立也大概率触发不了退出条件。
修复方案
先存储初始的本金金额,用初始本金的两倍作为固定的翻倍目标,循环条件改为判断当前余额是否小于这个固定目标即可。
修正后代码
# 中文提示版代码 balance = int(input("请输入Roth IRA账户初始存款金额:")) apr = int(input("请输入年化收益率(百分比数值):")) # 存储初始本金,设置固定翻倍目标 initial_balance = balance target = 2 * initial_balance month = 0 while balance < target: added_interest = balance * (apr / 100) / 12 balance = balance + added_interest month +=1 formatted_balance = "${:.2f}".format(balance) print(f"第{month}个月后的账户余额: {formatted_balance}") print(f"在{apr}%的年化收益率下,你的投资需要{month}个月就能翻倍")
# 原版提示兼容代码 balance = int(input("Enter an initial Roth IRA deposit amount:")) apr = int(input("Enter an annual percent rate of return:")) # 存储初始本金,设置固定翻倍目标 initial_balance = balance target = 2 * initial_balance month = 0 while balance < target: added_interest = balance * (apr / 100) / 12 balance = balance + added_interest month +=1 formatted_balance = "${:.2f}".format(balance) print("Value after month", month,":", formatted_balance) print("It will take", month, "months to double your investment with a", apr, "% return")
内容的提问来源于stack exchange,提问作者kamoney
相关产品推荐
相关产品推荐

