1

我正在尝试用python制作一个计算信用卡余额的程序。这是麻省理工学院开放课件“计算机科学与编程导论”。我正在做问题集一

该程序必须要求用户提供起始变量:起始余额、年利率和最低每月付款。这是我的代码。

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))

如何让余额正确更新?我不知道如何在每个月底更新余额。到目前为止,每个月都会返回相同的最低每月付款、已付本金和剩余余额的值。

4

2 回答 2

0

您希望将变量保留在newBalance循环之外,否则每次迭代都会重新分配它。此外,您不想将利率除以余额的 12 倍,而是将其除以 12,然后将商乘以余额。最后,如上所述,您不需要所有的floats.

这应该有效:

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))
于 2013-10-16T22:20:18.103 回答
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))
于 2013-10-16T22:05:31.153 回答