问题是使用二等分搜索来查找薪水中要在3年内节省的部分,以支付定金。我的代码无法实现测试用例。我的代码似乎没有问题?
要满足的测试用例:
测试案例1
测试案例2
测试案例3
我得到的结果如下
测试案例1
测试案例2
测试案例3
annual_salary = int(input("Enter your annual salary: "))
the_annual_salary = annual_salary
total_cost = 1000000
semi_annual_raise = 0.07
portion_down_payment = 0.25
r = 0.04
num_months = 36
num_steps = 0
high = 10000
low = 0
guess = (high+low) / 2
current_savings = 0
while abs(current_savings - (portion_down_payment * total_cost)) > 100:
current_savings = 0
annual_salary = the_annual_salary
for i in range(num_months):
current_savings += current_savings * r/12
current_savings += annual_salary * (guess/10000) /12
if num_months % 6 == 0:
annual_salary += semi_annual_raise * annual_salary
if current_savings < portion_down_payment * total_cost:
low = guess
if guess == 10000:
break
elif current_savings > portion_down_payment * total_cost:
high = guess
num_steps += 1
guess = (high+low) / 2
if (guess == 10000) and (current_savings < portion_down_payment * total_cost + 100):
print("It is not possible to pay for the down payment in 36 months")
else:
print("Percent of salary to save is", guess/10000)
print("Number of steps taken:", num_steps)
答案 0 :(得分:0)
哦,我发现了问题... =。=
在if语句中,应将i替换为num_months,因为i是循环中使用的临时变量。
for i in range(num_months):
current_savings += current_savings * r/12
current_savings += annual_salary * (guess/10000) /12
if i % 6 == 0:
annual_salary += semi_annual_raise * annual_salary
获得的结果
测试案例1
测试案例2
测试案例3