【发布时间】:2020-08-09 16:06:21
【问题描述】:
这是 6.0001 MIT Intro to CS course PS1-C 中的一个问题:
为什么我必须两次定义某些变量——当定义没有改变时,在while循环内部和外部?例如,diff_from_target 或 current_savings 变量。
完整代码如下:
# User inputs
total_cost = 1000000
starting_annual_salary = 300000
semi_annual_raise = .07
# bisection search
low = 0
high = 10000
steps = 0
# Investments (investment = current_savings * monthly rate)
r = .04
monthly_rate = r/12
# Calculate down payment (target savings)
target_savings = .25 * total_cost
current_savings = 0
diff_from_target = target_savings - current_savings
savings_rate = (low+high)/2
while abs(diff_from_target) > 100 and steps < 100:
months = 0
current_savings = 0
annual_salary = starting_annual_salary
savings_rate = (low+high)/2
while months < 36:
current_savings += (annual_salary/12)*savings_rate + current_savings * monthly_rate
months += 1
if months % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
diff_from_target = target_savings - current_savings
if diff_from_target > 0:
low = savings_rate
elif diff_from_target < 0:
high = savings_rate
steps +=1
else:
if abs(diff_from_target) <= 100:
print("%: {0:.4f}, steps: {1}".format(savings_rate, steps))
else:
print("Not possible to 36 months")
【问题讨论】:
-
我猜这是代码通过
else部分的情况