关于不改变N的价值

时间:2015-09-06 18:40:58

标签: python canopy

问题是在 -

时找到您需要向信用卡公司支付的固定金额
  • bal =您在第0个月初需要支付的金额
  • N =这是每月支付给信用卡公司的固定金额,以便在年底支付总金额
  • int =信用卡公司的利率
bal = int(raw_input("Enter balance"))
rate = int(raw_input("enter rate"))
lower_b = bal/12
upper_b = (bal + ((rate*bal)/1200))/12
N= (lower_b+upper_b)/2
def Credit(bal,rate,N):
        global upper_b
        global lower_b
        i=1
        k=bal
        while (i<13):
            print(N)
            paid = N
            bal = bal - paid
            print("Balance remains to be paid is %s" %(round(bal,2)))
            Interest = rate * bal /1200
            print("The interest added on is %s" %(round(Interest,2)))
            bal=bal+Interest
            print ("The amount that needs to be payed is %s " %(round(bal,2)))
            i=i+1

        if bal==0:
            return N
        elif  50 < bal < 2000 :
            lower_b = N
            upper_b = upper_b
            N = (upper_b +lower_b)/2
            return Credit(k,rate,N)
        elif -2000<bal< -50:
            upper_b = N
            lower_b = lower_b
            N = (lower_b +upper_b)/2
            return Credit(k,rate,N)
        elif  -50 < bal < 50:
            return N 
        else:
            return bal


result=Credit(bal,rate,N)
print(result)

我的代码永远不会终止。问题是代码中定义的N值没有变化。它保持固定N = upper_b + lower_b)/ 2

1 个答案:

答案 0 :(得分:0)

使用递归不是理想的方法,你也有逻辑错误,包括需要获得当月的利率,你的初始上限应该大于本金加利息。在每个不成功的内部循环之后,您可以使用带有内部for循环的while循环重置平衡:

balance = int(raw_input("Enter balance"))
int_rate = float(raw_input("enter rate"))
int_rate /= 100
lower_b = balance / 12.
upper_b = ((balance * (1 + (int_rate / 12.0)) ** 12) / 12.0)
payment = (lower_b + upper_b) / 2
def Credit(bal, rate, low, high, pay):
    new_b = bal
    # calculate monthly interest rate
    month_int = rate / 12
    while abs(new_b) > 0.001:  # use epsilon 
        # always reset balance
        new_b = bal
        for _ in range(12):  # loop over 12 month range
            new_b -= pay  # deduct pay
            new_b += month_int * new_b
        # if we still have a balance we need to take more so set low to current payment
        if new_b > 0:
            low = pay
        # else we took to much so set high to current payment
        else:
            high = pay
        pay = (low + high) / 2.0
    return "Lowest monthly payment over 12 months: {}".format(pay)


print(Credit(balance, int_rate, lower_b, upper_b, payment))