问题是编写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}$
Decimal(input())
的用法错误:使用
^{pr2}$input
会导致Python计算输入值,从而创建一个浮点值。通过使用raw_input
并将字符串直接传递给Decimal
来解决此问题:将代码缩进4个空格,紧跟PEP 8,并避免使用单字符变量名。在
这里有一个与你的写作方式非常相似的答案。使用我在询问how to round off a floating number in python时解释和建议的方法,它使用
decimal
模块等效的math
模块的ceil
函数来获得与实践链接相同的答案(除了一些次要的输出格式)。我还将代码重新缩进了更常用的4个空格,并将变量重命名为可读性更强一些。希望你能从中学到一些东西。请注意,我没有将decimal.getcontext().prec
设置为3
(我不相信它会像您所想的那样)。在首先,我建议不要同时做}。挑一个,然后用你需要的。通常,我使用
import decimal
和{import whatever
,然后使用whatever.what_is_needed
来保持名称空间的整洁。在正如评论者已经指出的,没有必要为这么简单的事情创建一个类(除非这是家庭作业,而且你的老师需要它)。删除类声明,将您的
def __init__(self)
更改为def main()
,并在当前实例化loan\u类的地方调用main。有关主函数的更多信息,请参见Guido's classic post关于它们。在应检查输入值。一种简单的方法是使用try-except块将它们转换为十进制。代码可能看起来像:
要使其工作,您必须在系统出口()打电话。我通常把我的导入放在文件的开头。在
因为所有的输入都是同一类型的,所以可以很容易地将此函数设为通用函数,然后为每个输入调用该函数。在
在计算中似乎确实存在某种缺陷。解决这个问题是留给读者的练习。;—)
相关问题 更多 >
编程相关推荐