我正在尝试在python中创建一个计算信用卡剩余余额的程序。这是麻省理工学院开放课件"Introduction to Computer Science and Programming"。我正在做problem set one。
程序必须询问用户启动变量:起始余额,年利率和最低月付款。 这是我的代码。
initialOutstandingBalance= float(raw_input('What is the outstanding balance on your
card?'))
annualInterestRate=float(raw_input('What is the annual interest rate expressed as a
decimal?'))
minimumMonthlyPaymentRate=float(raw_input('What is the minimum monthly payment rate on
your card expressed as a decimal?'))
for month in range(1,13):
print("Month: "+ str(month))
minimumMonthlyPayment=float(minimumMonthlyPaymentRate*initialOutstandingBalance)
interestPaid=float((annualInterestRate)/(12*initialOutstandingBalance))
principalPaid=float(minimumMonthlyPayment-interestPaid)
newBalance=float(initialOutstandingBalance-principalPaid)
print("Minimum monthly payment: $"+str(minimumMonthlyPayment))
print("Principle paid: $"+str(principalPaid))
print("Remaining Balance: $"+str(newBalance))
如何让剩余余额正确更新?我无法弄清楚如何在每个月末更新余额。到目前为止,每个月都会返回最低月付款,已付本金和余额的相同值。
答案 0 :(得分:0)
您在整个循环中使用相同的initialOutstandingBalance
变量,并且从不更改它。相反,您应该跟踪当前的余额。这将等于循环开始时的初始未结余额,但会在运行时发生变化。
您也无需继续致电float
。
current_balance = initialOutstandingBalance
for month in range(1,13):
print("Month: "+ str(month))
minimumMonthlyPayment = minimumMonthlyPaymentRate * current_balance
# this calculation is almost certainly wrong, but is preserved from your starting code
interestPaid = annualInterestRate / (12*current_balance)
principalPaid = minimumMonthlyPayment - interestPaid
current_balance = current_balance - principalPaid
print("Minimum monthly payment: $"+str(minimumMonthlyPayment))
print("Principle paid: $"+str(principalPaid))
print("Remaining Balance: $"+str(current_balance))
答案 1 :(得分:0)
您希望将变量newBalance
保留在循环之外,否则每次迭代都会重新分配。此外,您不希望将利率除以余额的12倍,而是将其除以12,然后将商乘以余额。最后,如上所述,您不需要所有float
个。
这应该有效:
newBalance = initialOutstandingBalance
for month in range(1,13):
print("Month: " + str(month))
minimumMonthlyPayment = minimumMonthlyPaymentRate * newBalance
interestPaid = annualInterestRate / 12 * newBalance
principalPaid = minimumMonthlyPayment - interestPaid
newBalance -= principalPaid
print("Minimum monthly payment: $" + str(minimumMonthlyPayment))
print("Principle paid: $" + str(principalPaid))
print("Remaining Balance: $" + str(newBalance))