如何编写python程序来计算月利率,同时显示年输出?

2024-10-17 06:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个程序,计算和打印贷款余额随时间的推移。程序必须(按顺序)要求用户提供以下内容:

贷款金额,即本金(浮动)。 年利率为1.0的分数(浮动)。 用户任意选择的月支付金额(浮动;金额未计算)。 贷款期限以年为单位(int)。 贷款是本金和利息,这个程序模拟每月支付固定金额的贷款。利息在定期付款前按月计算

请注意,该程序必须每月计算本金和利息变化,但每年只打印一次更新。对于这个问题,余额为负是可以的

运行程序时应完全像以下所示:

Principal? 100000
Interest rate? 0.055
Monthly repayment? 1000.00
Term in years? 5
Year       Opening      Closing
   0    100,000.00    93,333.62
   1     93,333.62    86,291.20
   2     86,291.20    78,851.53
   3     78,851.53    70,992.21
   4     70,992.21    62,689.55

输出必须格式化为小数点后两位,对齐方式如图所示。。数字有11个字符宽,带有逗号分隔符和两个小数位。我编写了以下程序,但没有得到所需的输出:

principal = float(input('Principal? '))
interest = float(input('Interest rate? '))
payment = float(input('Monthly repayment? '))
Term = int(input('Term in years? '))
payment = 1000
n = 1
p = 0
opening = principal
m_opening = 0
m_closing = 0
rate = 0
closing = 0
i=0
year = 0
m = 0
print(f'Year       Opening      Closing')
for i in range (Term):
  if year == 0:
    while n<=12:
      rate = opening*interest/12
      closing = opening - (payment-rate)
      opening = closing
      n = n+1
    m = closing
    opening = principal
    print(f'  {year:2}   {opening:11,.2f}  {closing:11,.2f}')
    year = year+1
  else:
    n=1
    while n<=12:
      rate = opening*interest/12
      closing = opening - (payment-rate)
      opening = closing
      n = n+1
    print(f'  {year:2}   {opening:11,.2f}  {closing:11,.2f}')
    year = year+1

我的输出如下:

Principal? 100000
Interest rate? 0.055
Monthly repayment? 1000
Term in years? 5
Year       Opening      Closing
   0    100,000.00    93,333.62
   1     93,333.62    93,333.62
   2     86,291.20    86,291.20
   3     78,851.53    78,851.53
   4     70,992.21    70,992.21

Tags: in程序principalinputratepayment金额year
1条回答
网友
1楼 · 发布于 2024-10-17 06:14:20

您需要在第一年之后保留一年的期初,当然您每次都要修改期初变量。你也不需要m=关闭和打开=主体。找到下面的slightmodified工作代码

principal = float(input('Principal? '))
interest = float(input('Interest rate? '))
payment = float(input('Monthly repayment? '))
Term = int(input('Term in years? '))
payment = 1000
n = 1
p = 0
opening = principal
m_opening = 0
m_closing = 0
rate = 0
closing = 0
i = 0
year = 0
m = 0
print(f'Year       Opening      Closing')
for i in range(Term):
    if year == 0:
        while n <= 12:
            rate = opening * interest / 12
            closing = opening - (payment - rate)
            opening = closing
            n = n + 1
        # m = closing
        # opening = principal
        print(f'  {year:2}   {principal:11,.2f}  {closing:11,.2f}')
        year = year + 1
    else:
        n = 1
        yearOpening = closing
        while n <= 12:
            rate = opening * interest / 12
            closing = opening - (payment - rate)
            opening = closing
            n = n + 1
        print(f'  {year:2}   {yearOpening:11,.2f}  {closing:11,.2f}')
        year = year + 1

输出:

enter image description here

希望有帮助

相关问题 更多 >