class creditCard:
def __init__(self,limit, apr, balance):
self.limit = limit
self.apr = apr
self.balance = balance
self.charges = {}
self.payments = {}
def charge(self, amount, day):
if amount > self.limit - self.balance:
return False
self.charges[day] = amount
self.balance += amount
def payment(self, amount, day):
if amount > self.limit - self.balance:
return False
self.payments[day] = amount
self.balance -= amount
def interest(self, balance):
return (balance * self.apr) / 365
def days_balance(self, balance_day):
balance_to_date = 0
months_interest = 0
for day in range(1, balance_day+1):
balance_to_date += self.charges.get(day, 0)
balance_to_date -= self.payments.get(day, 0)
months_interest += self.interest(balance_to_date)
if day % 30 == 0:
balance_to_date += months_interest
months_interest = 0
return round(balance_to_date, 2)
我有这个程序,我写的一个任务,其中的方向非常混乱(我将在下面发布)但我得到两个测试用例,我通过我的第一个测试用例,但我的第二个测试用例我必须做数学或逻辑错误?函数days_balance()
应返回411.99但返回411.89我使用相同的函数来计算我的第一个测试用例的兴趣,所以我不明白为什么它在我的第二个测试用例中不能正常工作。任何见解或建议将不胜感激。
路线:
给出信用卡:
软件应该:
测试用例:
测试案例2:
以下是我如何调用每个方法(我的测试)
测试1:
customer1 = creditCard(1000, 0.35, 0)
customer1.charge(500, 1)
print(customer1.days_balance(30))
测试2:
customer2 = creditCard(1000, 0.35, 0)
customer2.charge(500, 1)
customer2.payment(200, 15)
customer2.charge(100, 25)
print(customer2.days_balance(30))
答案 0 :(得分:0)
您计算30天后的预期余额如下:
((500 * 0.35) / 365) * 15 + ((300 * 0.35) / 365) * 10 + ((400 * 0.35) / 365) * 5 ~= 411.99
您的代码会像这样计算余额:
((500 * 0.35) / 365) * 14 + ((300 * 0.35) / 365) * 10 + ((400 * 0.35) / 365) * 6 ~= 411.89
这看起来像是经典的一次性错误。我建议严格遵守0索引代码以避免这些。
您可以在方法中插入打印调用,以了解months_interest
如何演变:
def days_balance(self, balance_day):
balance_to_date = 0
months_interest = 0
for day in range(1, balance_day+1):
balance_to_date += self.charges.get(day, 0)
balance_to_date -= self.payments.get(day, 0)
months_interest += self.interest(balance_to_date)
if day % 30 == 0:
balance_to_date += months_interest
months_interest = 0
print(day, months_interest, balance_to_date)
return round(balance_to_date, 2)
再考虑一下,我认为你的代码做了它应该做的事情,但测试用例的逻辑是关闭的。如果客户在第25天收取100个款项并且在第30天支付利息,那么该帐户将在+400持续6天。