我的程式應該告訴用戶他們的投資賬戶中的資金翻倍需要多少個月。我能夠正確地進行計算,但是我無法跳出回圈并列印出告訴用戶最后一句話“將需要 x 個月的時間以 y% 的回報將您的投資翻倍”的陳述句。
balance = int(input("Enter an initial Roth IRA deposit amount:"))
apr = int(input("Enter an annual percent rate of return:"))
month = 0
while balance != 2*balance:
added_interest = balance * (apr / 100) / 12
balance = balance added_interest
month =1
formatted_balance = "${:.2f}".format(balance)
print("Value after month", month,":", formatted_balance)
if balance == 2*balance:
break
print("It will take", month, "months to double your investment with a", apr, "% return")
uj5u.com熱心網友回復:
你的問題是,測驗balance針對2*balance始終測驗電流平衡,不增加一倍的初始平衡。最初只需存盤計算的雙倍余額,并測驗當前余額是否仍然小于該余額(不需要單獨的if/ break,您的while條件會處理它):
balance = int(input("Enter an initial Roth IRA deposit amount:"))
apr = int(input("Enter an annual percent rate of return:"))
month = 0
doubled_balance = 2 * balance # Store off doubled initial balance
while balance < doubled_balance: # Check current balance against doubled initial,
# and use <, not !=, so you stop when you exceed it,
# not just when you're exactly equal
added_interest = balance * (apr / 100) / 12
balance = balance added_interest
month =1
formatted_balance = "${:.2f}".format(balance)
print("Value after month", month,":", formatted_balance)
# No need for if/break
print("It will take", month, "months to double your investment with a", apr, "% return")
綜上所述,這根本不需要回圈。初始余額無關緊要(在固定回報率的情況下,將 1 美元加倍與將 1000 美元加倍所需的時間一樣長,忽略四舍五入誤差),因此這簡化為 APR 到 APY 的簡單轉換以考慮每月復利,然后通過對數計算來確定達到 2(翻倍)所需的 APY 的冪,然后從幾個月轉換為幾年并向上取整(因為到那個月底你不會翻倍):
import math
apr = int(input("Enter an annual percent rate of return:"))
apr_decimal = apr / 100
apy = (1 (apr_decimal / 12)) ** 12 # Standard APR to APY computation for monthly compounding
months = math.ceil(math.log(2, apy) * 12) # Compute the power (years) of APY to double the investment
# then multiply by 12 and round up to a full month
print("It will take", months, "months to double your investment with a", apr, "% return")
uj5u.com熱心網友回復:
在您的比較中,您balance與2*balance. 顯然balance == 2*balance將永遠是false,如果balance > 0。因此,如果有人計劃投資超過 0 美元的任何東西,您的代碼將永遠停留在那里。
您需要一個新變數來存盤更新后的余額和回報率:
# assuming you have balance and apr set
newBalance = balance # balance returned amount
month = 0
while newBalance < 2*balance:
# replace ! with <, so that loop breaks when newBalance >= 2*balance
added_interest = newBalance * (apr / 100) / 12
newBalance = newBalance added_interest
month =1
formatted_balance = "${:.2f}".format(newBalance)
print("Value after month", month,":", formatted_balance)
上面的代碼假設增加的利息是根據newBalance價值計算的。如果這對您不起作用,請告訴我。稍后我會除錯它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/319239.html
