如何用Python按年份区间展示复利的总金额、本金及已获利息?
实现复利年份区间表格展示的改进方案
首先修正你代码中的缩进问题(最后两行执行代码被缩进在compound_interest函数内,无法正常运行),然后新增年份区间表格展示的功能,以下是改进后的完整代码:
def get_time(): year = float(input("enter year: ")) month = float(input("enter months: ")) day = float(input("enter days: ")) # 转换为总年数 total_years = year + month/12 + day/365 print(f"total time in years is: %.2f" % total_years) return total_years def calculate_compound_interest(principal, rate, compound_period, years): # 复利计算公式 return principal * ((1 + (rate/100)/compound_period) ** (compound_period * years)) def generate_yearly_breakdown(principal, rate, compound_period, total_years): breakdown = [] # 处理完整的年份 full_years = int(total_years) remaining_years = total_years - full_years # 计算每一年的期末金额 for year in range(1, full_years + 1): current_amount = calculate_compound_interest(principal, rate, compound_period, year) interest_earned = current_amount - principal breakdown.append({ "年份区间": f"第{year}年", "总金额": round(current_amount, 2), "本金": principal, "已获利息": round(interest_earned, 2) }) # 处理剩余不足一年的部分 if remaining_years > 0: final_amount = calculate_compound_interest(principal, rate, compound_period, total_years) interest_earned = final_amount - principal breakdown.append({ "年份区间": f"第{full_years+1}年({remaining_years:.2f}年)", "总金额": round(final_amount, 2), "本金": principal, "已获利息": round(interest_earned, 2) }) return breakdown def print_breakdown_table(breakdown): # 打印格式化表格 print(f"| {'年份区间':<15} | {'总金额':<10} | {'本金':<8} | {'已获利息':<10} |") print("|-----------------|------------|----------|------------|") for entry in breakdown: print(f"| {entry['年份区间']:<15} | {entry['总金额']:<10.2f} | {entry['本金']:<8.2f} | {entry['已获利息']:<10.2f} |") # 主程序执行 if __name__ == "__main__": total_years = get_time() principal = float(input("enter principal: ")) rate = float(input("enter rate: ")) compound_period = float(input("enter compounding period: ")) # 打印最终总金额 final_amount = calculate_compound_interest(principal, rate, compound_period, total_years) print(f"final amount after {total_years:.2f} years is {final_amount:.2f}") # 生成并打印年份区间明细表格 print("\n--- 年份区间复利明细 ---") breakdown = generate_yearly_breakdown(principal, rate, compound_period, total_years) print_breakdown_table(breakdown)
关键改动说明
- 修复执行逻辑:将原代码中缩进错误的主执行代码移到函数外,确保程序能正常启动。
- 拆分复用逻辑:把复利计算单独抽成
calculate_compound_interest函数,方便重复计算不同年份的金额。 - 生成区间明细:
generate_yearly_breakdown函数会按「完整年份+剩余不足一年」的区间,分别计算每个阶段的总金额、本金和已获利息。 - 格式化表格输出:
print_breakdown_table函数用对齐的表格形式打印明细,可读性更强。
示例输出
假设输入:
enter year: 2 enter months: 6 enter days: 73 enter principal: 1000 enter rate: 5 enter compounding period: 12
输出效果:
total time in years is: 2.70 final amount after 2.70 years is 1143.47 --- 年份区间复利明细 --- | 年份区间 | 总金额 | 本金 | 已获利息 | |-----------------|------------|----------|------------| | 第1年 | 1051.16 | 1000.00 | 51.16 | | 第2年 | 1104.94 | 1000.00 | 104.94 | | 第3年(0.70年) | 1143.47 | 1000.00 | 143.47 |
内容的提问来源于stack exchange,提问作者BeanBagInaHurry
相关产品推荐
相关产品推荐

