gpt4 book ai didi

python - 计算 for 循环期间的运行总计 - Python

转载 作者:行者123 更新时间:2023-12-02 01:20:39 25 4
gpt4 key购买 nike

编辑:下面是我根据收到的反馈/答案编写的工作代码。

这个问题源于我之前使用 MIT 的开放课件学习 Python/CS 时提出的问题。 -- See my previous question here --

我正在使用以下代码来列出每月付款和其他事项的列表。然而,在循环结束时,我需要给出当月已支付的总金额的运行总计。

原始代码

balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))

for month in xrange(1, 12+1):
interestPaid = round(interestRate / 12.0 * balance, 2)
minPayment = round(minPayRate * balance, 2)
principalPaid = round(minPayment - interestPaid, 2)
remainingBalance = round(balance - principalPaid, 2)


print 'Month: %d' % (month,)
print 'Minimum monthly payment: %.2f' % (minPayment,)
print 'Principle paid: %.2f' % (principalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)

balance = remainingBalance

if month in xrange(12, 12+1):
print 'RESULTS'
print 'Total amount paid: '
print 'Remaining balance: %.2f' % (remainingBalance,)

问题是我无法弄清楚如何保持支付金额的累计总额。我尝试添加 totalPaid = round(interestPaid +principalPaid, 2) 但这只会导致一个月的总计,我似乎无法让它保留每个月的该值,然后将它们全部添加放在最后打印出来。

我还知道结果金额应该是 1131.12

我发现了许多通过列表知道每个值时执行此操作的示例,但我似乎无法正确推断。

固定代码

balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))
totalPaid = 0

for month in xrange(1, 12+1):
interestPaid = round(interestRate / 12.0 * balance, 2)
minPayment = round(minPayRate * balance, 2)
principalPaid = round(minPayment - interestPaid, 2)
remainingBalance = round(balance - principalPaid, 2)
totalPaid += round(minPayment, 2)

print 'Month: %d' % (month,)
print 'Minimum monthly payment: %.2f' % (minPayment,)
print 'Principle paid: %.2f' % (principalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)

balance = remainingBalance

if month in xrange(12, 12+1):
print 'RESULTS'
print 'Total amount paid: %.2f' % (totalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)

最佳答案

在循环之前,初始化一个变量来累加值:

total_paid = 0

然后,在循环体中添加适当的数量。您可以使用 += 运算符添加到现有变量,例如

total_paid += 1

total_paid =total_paid + 1的缩写形式。您不想每次迭代都为 total_paid 提供新值,而是希望添加到其现有值。

我不确定您的问题的具体情况,但这是循环时累积值的一般形式。

关于python - 计算 for 循环期间的运行总计 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4997859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com