[英]Investment calculator refuses to calculate properly
我的程序運行但絕對不是它的本意。 無論我輸入哪個,它總是說“你賺了:0.00 美元”,我嘗試將“months_invested = years_investment / 12”移動到多個地方,甚至添加或刪除位。
投資計算器旨在每月計算這些東西,但我似乎無法正確計算。 一個問題變成兩個問題,這對我來說就像九頭蛇,你解決了一件事情,它就會成倍增加。
"""
InvestmentCalculator.py helps generate how much interest one earns after a certain period of time
"""
def main():
total_money = 0
months_invested = 0
years_investment = 0
investment = float(input("How much would you like to invest? "))
years_investment = float(input("How many years would you like to invest? "))
interest_rate = float(input("What is the interest rate? "))
total_money = float()
months_invested = float()
while months_invested > 0:
months_invested = (years_investment / 12) - 1
total_money = investment + total_money
print("You have earned ${:,.2f}".format(total_money))
else: print("You've earned a total of ${:,.2f}".format(total_money))
main()
我有一種感覺,這就是您要實現的目標。 需要進行一些調整,我將在代碼下方進行解釋:
def main():
total_money = float(input("How much would you like to invest? "))
years_investment = float(input("How many years would you like to invest? "))
interest_rate = float(input("What is the monthly interest rate in %? "))
months_invested = years_investment * 12
while months_invested > 0:
interests = interest_rate / 100 * total_money
total_money += interests
print("You have earned ${:,.2f}".format(total_money))
months_invested += -1
main()
輸出:
You have earned $101.00
You have earned $102.01
You have earned $103.03
You have earned $104.06
You have earned $105.10
You have earned $106.15
You have earned $107.21
You have earned $108.29
You have earned $109.37
You have earned $110.46
You have earned $111.57
You have earned $112.68
正如 G.Anderson 所說,沒有必要用值 0(或任何值)初始化變量。 只需將其定義為輸入即可。
月投資公式錯誤,困擾循環。 此外,如果這是固定的,循環將無限運行,因為沒有限制或條件可以結束它(這就是months_invested += -1
的目的。每次循環通過時減少變量的值,以便它停止某個時候(也就是說,當沒有更多的投資月份時)。
最后記住你的函數正在打印結果而不返回任何東西,所以提前使用它時要小心。
如果您需要復利(每月),那么您應該使用復利公式。 即(((1+i) ** months) -1) * $
。 在這種情況下,我使用total_money += interests
將期間產生的利息加到資金總額中,這些資金將在下一期間再投資(因此,復利)。
沒有真正需要使用 while 循環,其他方法可能更有效,例如使用列表或數組。 但是,對於我的回答,我尊重您代碼的原始結構。
months_invested
由行設置months_invested = float()
,它被初始化為零。 這意味着 while 循環永遠不會運行。 你想要months_invested = years_investment * 12
。
值得注意的是,這仍然不會如你所願,但我不想為你提供完整的答案:與問題作斗爭是學習的重要組成部分。
你在這里有幾件事。
float()
改變。years_investment = 0
之后的所有內容都不在main()
函數中。 (這可能只是發布問題時的復制/粘貼問題。)months_investment
值。我做了一些重構,讓你到達我認為你想去的地方。
def main():
investment = float(input("How much would you like to invest? "))
months_investment = float(int(input("How many years would you like to invest? ")) * 12)
interest_rate = float(input("What is the interest rate? "))
total_money = 0
while months_investment > 0:
total_money += investment * interest_rate
print("You have earned ${:,.2f}".format(total_money))
months_investment -= 1
else: print("You've earned a total of ${:,.2f}".format(total_money))
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.