为什么我的四舍五入到两位小数对我的代码不起作用?

时间:2019-09-20 18:20:19

标签: python

一个学校项目要求我执行一个函数,该函数应返回四舍五入到小数点后两位数的月度付款的绝对值。

谁能解释我为什么我的代码无法正常工作?预先感谢!

interest_rate= int(input('Type your interest rate (in %) '))
principal = int(input('Type your principal '))
period = int(input('Type for how many months '))

def calculate_payment(principal, interest_rate, period):
    final_amount = (1 + interest_rate) ** period
    return principal * (interest_rate * final_amount) / 
    (final_amount- 1)

final_amount = str(round(final_amount, 2))

print("your amount that has to be paid after each month is: ", final_amount)

1 个答案:

答案 0 :(得分:1)

我认为,您既会误解复利的公式(除了堆栈溢出),也不会详细说明利率的期限(利率是每月还是每年?)。如果利率是每月,并且您将返回一个月后将支付的利息,那么可变期限是没有用的。关于代码,您没有正确定义函数,也没有正确调用它以使其起作用。此外,如果是复利,则每月支付的(利息)价值将永远不相等,因为除非利息被提取且不进行再投资。如果是您要的,请检查案例2 。情况1假设您要在操作完成时退还全部款项。

这是我认为您要寻找的:

案例1

interest_rate= int(input('Type your interest rate (in %) '))
principal = int(input('Type your principal '))
period = int(input('Type for how many months '))

def calculate_payment(principal, interest_rate, period):
    final_amount = principal * ((1+interest_rate/100) ** period)
    return round(final_amount,2)

print("your amount that has to be paid at the end of the period is: ", calculate_payment(principal, interest_rate,period))

输出:

Type your interest rate (in %) 10
Type your principal 1000
Type for how many months 2
your amount that has to be paid at the end of the period is:  1210.0

案例2

interest_rate= int(input('Type your monthly interest rate (in %) '))
principal = int(input('Type your principal '))
period = int(input('Type for how many months '))

def calculate_payment(principal, interest_rate, period):
    final_amount = principal * (((1+interest_rate/100)) - 1)
    return round(final_amount,2)

print("your amount that has to be paid after each month is: ", calculate_payment(principal, interest_rate,period))

输出:

Type your monthly interest rate (in %) 10
Type your principal 1000
Type for how many months 2
your amount that has to be paid after each month is:  100.0