我对Python完全陌生,在计算缩进时有很多问题,无论如何,我需要有人帮助我理解为什么我的代码不能工作…(if条件是不能从内部while循环中识别值)
balance = 1000
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate /12
episilon = 0.01
numGuesses = 0
Low = balance / 12
High = (balance * (1 + monthlyInterestRate )**12) / 12.0
ans = (Low + High) / 2.0
newbalance = balance
monthlyPayment = ans
while newbalance > 0:
newbalance = balance
month = 0
while month < 12:
print('low = ' + str(Low) + ' high = ' + str(High) + ' ans = ' + str(ans))
newbalance -= monthlyPayment
interest = monthlyInterestRate * newbalance
newbalance += interest
month += 1
print month
if(newbalance > 0):
Low = ans
else:
High = ans
ans = (Low + High) / 2.0
print 'Lowest payment: ' + str(ans)
您应该扣除
ans
而不是monthlyPayment
,在循环外设置monthlyPayment = ans
并不意味着每次在while循环内设置ans = (Low + High) / 2.0
时monthlyPayment
都会更新,每次您都在创建一个新对象:而且最好使用
for month in range(12)
,我们知道我们只希望有12次迭代,所以使用范围要简单得多。你知道吗即使您正在执行
ans += 2
,您的monthlyPayment
也不会更新,因为int是不可变的,所以monthlyPayment
仍然只会指向ans
的原始值。你知道吗相关问题 更多 >
编程相关推荐