[英]Have I made a mistake in my For loop in python code? Model accuracy is too high so double checking
[英]What mistake have i made in my code? Its running but not providing the answer that it should for the input i have shown
這是問題:
你已經從麻省理工學院畢業,現在有一份很棒的工作! 您搬到舊金山灣區並決定開始存錢買房子。 由於灣區的房價非常高,您意識到您將不得不儲蓄幾年才能負擔得起房屋的首付款。 在 A 部分,我們將根據以下假設確定您需要多長時間才能存夠足夠的錢來付款:
將您夢想中的家的成本稱為“i”。
將您迄今為止保存的金額稱為“當前”。 您從當前節省的 0 美元開始。
假設您明智地投資您當前的儲蓄,年度回報為 r(換句話說,在每個月末,您會收到額外的“當前*r/12”資金用於存入您的儲蓄——12 是因為 r是年費率)。 假設您的投資獲得 r = 0.04 (4%) 的回報。
假設你的年薪是 i。
假設您打算每個月將一定數量的薪水用於儲蓄以支付首付。 稱之為'p'。 此變量應為十進制形式(即 0.1 表示 10%)。
在每個月底,您的儲蓄將根據您的投資回報,加上您月薪的百分比(年薪 / 12)而增加。 編寫一個程序來計算你需要多少個月才能存夠足夠的錢來支付首付。 你會希望你的主要變量是浮點數,所以你應該將用戶輸入轉換為浮點數。
您的程序應該要求用戶輸入以下變量:
起薪年薪 (i)
要儲蓄的工資部分(p)
你夢想家園的成本 (c)
這是我的代碼:
i=int(input("Enter your annual salary:"))
p=float(input("Enter the percent of your salary to save, as a decimal:"))
c=float(input("Enter the cost of your dream home:"))
r=0
current=float(i*p*r/12)
for r in range(9999999):
if current<c:
current=current*(0.04)/12
else:
break
print("Number of months ="+ str( int(r)))
以下輸入所需的正確輸出是:
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months: 1000
但我得到的輸出是:
Enter your annual salary:120000
Enter the percent of your salary to save, as a decimal:.10
Enter the cost of your dream home:1000000
Number of months =9999998
誰能告訴我為什么我錯了?
PS:: 非常抱歉之前我上傳了一個稍微不同的問題; 我現在已經提供了相關的問題。
問題在這里:
current=current*(0.04)/12
在這一行中,您不累積,而只是覆蓋當前的值。
嘗試在紙上寫出您的解決方案,並問問自己是否有意義。
for r in range(9999999):
if current<c:
current=current*(0.04)/12
else:
break
print("Number of months ="+ str( int(r)))
我注意到的是,無論發生什么, current
都將始終為 0,因為如果current
沒有變化,則0 < 1000000
將始終為真。
current=current*(0.04)/12
本質上是0=0*(0.04)/12
,看看它怎么總是0?
當r
遍歷范圍內的所有 "9999999" 時, r
將在此之前停止,中斷並返回給您您注意到Number of months =9999998
。
代碼本身運行正常,但我會重新檢查邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.