如何修改Python投资计算代码,实现逐年度打印收益直至输入的指定年份
投资收益计算代码修改方案
核心问题说明
原代码的打印逻辑放在循环体外,只会在循环结束后执行一次,同时没有累计每年的利息得到总收益,也没有逐年记录对应数据。
完整修改后代码
# 读取用户输入 initial_invest = int(input("请输入初始投资金额: ")) invest_years = int(input("请输入投资年限: ")) rate = float(input("请输入年利率(单位%): ")) total_interest = 0 current_balance = initial_invest # 打印表头 print("="*40) print(f"{'投资年份':<8} {'年初余额':<12} {'当年利息':<12} {'年末余额':<12}") print("-"*40) # 逐年计算并打印 for year in range(1, invest_years + 1): year_interest = round(current_balance * (rate / 100), 2) end_balance = round(current_balance + year_interest, 2) # 打印当年数据 print(f"{year:<10} ${current_balance:<11.2f} ${year_interest:<11.2f} ${end_balance:<11.2f}") # 更新累计利息和下一年的年初余额 total_interest = round(total_interest + year_interest, 2) current_balance = end_balance # 打印累计汇总 print("="*40) print(f"初始投资金额: ${initial_invest:.2f}") print(f"投资期满总余额: ${current_balance:.2f}") print(f"累计总收益: ${total_interest:.2f}")
改动说明
- 把打印每年数据的逻辑移到循环内部,每次循环都输出当年的投资数据
- 增加了格式化的表头和分割线,输出结果更易读
- 新增了总利息累计逻辑,最后输出的总收益是多年利息的累加值,不会和单年利息混淆
- 变量名调整为更易读的命名,输入提示改为中文
内容的提问来源于stack exchange,提问作者CWoolford
相关产品推荐
相关产品推荐

