我的代码是这个作业的正确实现吗?

2024-10-16 20:40:38 发布

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

问题是编写python来计算贷款的到期利息并打印付款时间表。贷款的到期利息可根据以下简单公式计算:

I = P × R × T

其中I是支付的利息,p是借款金额(本金),R是利率,T是贷款期限。在

最后需要显示如下:

The program will print the amount borrowed, total interest paid, the amount of the monthly payment, and a payment schedule.

示例会话

Loan calculator

Amount borrowed: 100
Interest rate: 6
Term (years): 1

Amount borrowed:    $100.00
Total interest paid:  $6.00

           Amount     Remaining
Pymt#       Paid       Balance
-----      -------    ---------
  0        $ 0.00      $106.00
  1        $ 8.84      $ 97.16
  2        $ 8.84      $ 88.32
  3        $ 8.84      $ 79.48
  4        $ 8.84      $ 70.64
  5        $ 8.84      $ 61.80
  6        $ 8.84      $ 52.96
  7        $ 8.84      $ 44.12
  8        $ 8.84      $ 35.28
  9        $ 8.84      $ 26.44
 10        $ 8.84      $ 17.60
 11        $ 8.84      $  8.76
 12        $ 8.76      $  0.00

完整的问题描述如下:http://openbookproject.net/pybiblio/practice/wilson/loan.php 为此,我编写了如下代码:

^{pr2}$

Tags: the时间表payment金额amount公式利率贷款
3条回答

Decimal(input())的用法错误:

>>> decimal.getcontext().prec=3
>>> decimal.Decimal(input('enter the number: '))
enter the number: 0.1
Decimal('0.1000000000000000055511151231257827021181583404541015625')

使用input会导致Python计算输入值,从而创建一个浮点值。通过使用raw_input并将字符串直接传递给Decimal来解决此问题:

^{pr2}$

将代码缩进4个空格,紧跟PEP 8,并避免使用单字符变量名。在

这里有一个与你的写作方式非常相似的答案。使用我在询问how to round off a floating number in python时解释和建议的方法,它使用decimal模块等效的math模块的ceil函数来获得与实践链接相同的答案(除了一些次要的输出格式)。我还将代码重新缩进了更常用的4个空格,并将变量重命名为可读性更强一些。希望你能从中学到一些东西。请注意,我没有将decimal.getcontext().prec设置为3(我不相信它会像您所想的那样)。在

import decimal

def main():
    principle = decimal.Decimal(raw_input('Please enter your loan amount:'))
    rate = decimal.Decimal(raw_input('Please enter rate of interest (percent):')) / 100
    term = decimal.Decimal(raw_input('Please enter loan period (years):')) * 12

    interest = (principle * rate).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_HALF_EVEN)
    balance = principle + interest
    payment = (balance / term).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_CEILING)
    print "Payment\t\tAmount Paid\t\tRem.Bal."
    for count in range(1+term):
        if count == 0:
            print count, "\t\t0.00\t\t\t", balance
        elif count == term: # last payment?
            payment = balance
            balance -= payment
            print count, "\t\t", payment, "\t\t\t", balance
        else:
            balance -= payment
            print count, "\t\t", payment, "\t\t\t", balance

main()

# > python loan_calc.py
# Please enter your loan amount:100
# Please enter rate of interest (percent):6
# Please enter loan period (years):1
# Payment         Amount Paid             Rem.Bal.
# 0               0.00                    106.00
# 1               8.84                    97.16
# 2               8.84                    88.32
# 3               8.84                    79.48
# 4               8.84                    70.64
# 5               8.84                    61.80
# 6               8.84                    52.96
# 7               8.84                    44.12
# 8               8.84                    35.28
# 9               8.84                    26.44
# 10              8.84                    17.60
# 11              8.84                    8.76
# 12              8.76                    0.00

首先,我建议不要同时做import decimal和{}。挑一个,然后用你需要的。通常,我使用import whatever,然后使用whatever.what_is_needed来保持名称空间的整洁。在

正如评论者已经指出的,没有必要为这么简单的事情创建一个类(除非这是家庭作业,而且你的老师需要它)。删除类声明,将您的def __init__(self)更改为def main(),并在当前实例化loan\u类的地方调用main。有关主函数的更多信息,请参见Guido's classic post关于它们。在

应检查输入值。一种简单的方法是使用try-except块将它们转换为十进制。代码可能看起来像:

prin_str = raw_input('Please enter your loan amount: ')
try:
    principal = decimal.Decimal(prin_str)
except decimal.InvalidOperation:
    print "Encountered error parsing the loan amount you entered."
    sys.exit(42)

要使其工作,您必须在系统出口()打电话。我通常把我的导入放在文件的开头。在

因为所有的输入都是同一类型的,所以可以很容易地将此函数设为通用函数,然后为每个输入调用该函数。在

在计算中似乎确实存在某种缺陷。解决这个问题是留给读者的练习。;—)

相关问题 更多 >