![](/img/trans.png)
[英]Why does my python not show in cmd despite me adding the path to my system variables?
[英]why does this keep looping? despite me updating the appropriate variables
我多次查看此代碼,但我無法弄清楚到底出了什么問題? 此代碼應該詢問用戶輸入(房價、年薪、半年加薪、您願意等待買房的月數),然后輸出達到目標數量的最佳儲蓄率個月。 儲蓄也以 4% 的利率獲得利息。 使用二等分搜索。
print('what is the cost of your dream home?')
total_cost=float(input())
print ('what is your annual salary?')
annual_salary=float(input())
portion_down_payment=0.25*total_cost
current_savings=0
print('enter a semi-annual raise, as a decimal')
semi_annual_raise=float(input())
print('in how mnay months do you want to buy your house?')
target_months = int(input())
number_of_months=0
saving_rate=0
first=0
last=10000
steps_in_bisection=0
while target_months != number_of_months:
saving_rate= int((first+last)/2)
print ('ok')
print(number_of_months)
current_savings=0
number_of_months=0
while current_savings < portion_down_payment or current_savings-100< portion_down_payment :
current_savings += ((saving_rate/10000)*(annual_salary/12))+ (current_savings*0.04)/12
number_of_months=1+number_of_months
if number_of_months %6 == 0:
annual_salary+= semi_annual_raise * annual_salary
if number_of_months>target_months:
first=saving_rate
steps_in_bisection+=1
print ('here')
print(number_of_months)
elif number_of_months<target_months:
last=saving_rate
steps_in_bisection+=1
print('there')
print(number_of_months)
print("best savings rate: ", saving_rate)
print("number of months:",number_of_months)
例如,將內循環設為 function,然后將外循環設為 function,這將調用內循環。
您的外循環條件是不等式:
while target_months:= number_of_months:
有兩個問題:如果值不是整數,它可能會發生,你有非常相似但不完全相等的值,例如:1.0000001 和 1。
或者,該數字可能會跳過該確切值:
x = 5
while x != 0:
x = x - 2
在此段中,x 的值將是:5, 3, 1, -1, -3, -5, ... 但絕不會為 0,因此外觀將永遠是 go。
您在測試其值的循環(外循環)內設置值number_of_months=0
last
的值是任意設置為10000的,會不會太小了? 它應該取決於輸入的值嗎?
好吧,伙計們,我終於想通了。 在第二個 while 循環開始之前,應將年度工資設置回其原始用戶輸入值。 否則 anuual_salary 將繼續增加半年加薪金額,因此,隨着年薪不斷上漲,越來越低的儲蓄率將被接受。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.