Horuson 2022-07-16 21:51 采纳率: 100%

# python中二分法与控制流练习

###### 问题相关代码，请勿粘贴截图

semi_annual_raise = 0.07
annual_rate = 0.04
total_cost = 1000000
portion_down_payment = total_cost*0.25

annual_salary = float(input("enter your starting salary:"))
monthly_salary = annual_salary/12
saved_percent = 0
monthly_saving = monthly_salary*saved_percent
current_saving = 0
numMonth = 0

epsilon = 100
low = 0
high = 1
saved_percent = (low + high)/2
done = False
numGuesses = 0

while not done == True:
while numMonth <= 36:
current_saving = current_saving*(1+annual_rate/12) + monthly_saving
numMonth += 1
if numMonth % 6 == 0:
monthly_salary *= (1 + semi_annual_raise)

``````if abs(current_saving - portion_down_payment)>= epsilon:
if current_saving < portion_down_payment:
low = saved_percent
else:
high = saved_percent
saved_percent = (low + high)/2
numGuesses += 1
numMonth = 0
else :
done = True

``````

print("Best saving rate is", saved_percent)
print("Steps in bisection search:", numGuesses)

• 写回答

#### 1条回答默认 最新

• 请叫我问哥 Python领域新星创作者 2022-07-17 02:45
关注

修改如下：

``````semi_annual_raise = 0.07
annual_rate = 0.04
total_cost = 1000000
portion_down_payment = total_cost*0.25

annual_salary = float(input("enter your starting salary:"))
monthly_salary = annual_salary/12
saved_percent = 0
current_saving = 0
numMonth = 0

epsilon = 100
low = 0
high = 1
saved_percent = (low + high)/2
done = False
numGuesses = 0

while not done == True:
while numMonth <= 36:
monthly_saving = monthly_salary*saved_percent
current_saving = current_saving*(1+annual_rate/12) + monthly_saving
numMonth += 1
if numMonth % 6 == 0:
monthly_salary *= (1 + semi_annual_raise)
if abs(current_saving - portion_down_payment)>= epsilon:
if current_saving < portion_down_payment:
low = saved_percent
else:
high = saved_percent
saved_percent = (low + high)/2
monthly_salary = annual_salary/12
current_saving = 0
numGuesses += 1
numMonth = 0
else :
done = True

print("Best saving rate is", saved_percent)
print("Steps in bisection search:", numGuesses)
``````

试运行结果：

``````enter your starting salary:120000
Best saving rate is 0.531982421875
Steps in bisection search: 11
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

• 系统已结题 7月25日
• 已采纳回答 7月17日
• 修改了问题 7月16日
• 创建了问题 7月16日

#### 悬赏问题

• ¥15 单片机配网，继电器开关，广播
• ¥60 Qcustomplot绘制实时动态曲线
• ¥20 运用matlab画x-y图
• ¥15 用idea运行项目，运行tomcat报错：断言失败
• ¥15 Sqlserver查询链接服务器数据问题
• ¥15 Bibtex4Word 引用中文文献
• ¥20 用opencv c/c++ 转换成灰度图，然后做一下直方图均衡，输出mp4文件
• ¥20 matlab中的双层数值积分
• ¥50 服务器打印水晶报表问题