2016-03-04 65 views
0

每當我運行此操作時,它只會繼續獲取p值,而不是計算出的賬戶未來值?!當用戶輸入現值,利率和年數時,計算賬戶的未來價值

def main(): 
    p=eval(input("Enter in the present value of the account: ")) 
    i=eval(input("Enter in the monthly interest rate(%): ")) 
    I=eval(str(i//100)) 
    t=eval(input("Enter the number of months that that the money will be in the account: ")) 

    print(futureValue(p, I, t),"Is the future value of your account!") 

def futureValue(p, I, t): 
    return p*((1 + I) ** t) 

main() 
+1

對於所有這一切的愛是聖潔的,___不是'eval'原始用戶input___。即使我們忽略了整個「安全問題的定義」,也意味着用戶的小錯別字可以完成意想不到的事情,而且無法開始預測或處理。如果目標是轉換爲「int」或「float」或「decimal.Decimal」,則使用它們的構造函數。如果目標是接受'int'或'float'或任何其他Python文字,請使用['ast.literal_eval'](https://docs.python.org/3/library/ast.html#ast.literal_eval) ,它接受Python文字,但不是任意代碼。 – ShadowRanger

回答

2

這是因爲你在i//100而非/使用//。這將導致i/100的結果向下舍入,因此總是導致0.0只要i < 100(情況就是這樣)。這就是爲什麼你的未來價值總是和你現在一樣,因爲你把錢放在沒有興趣

簡單的改變:

I=eval(str(i//100)) 

到:

I=eval(str(i/100)) 

而且,因爲你從來沒有真正需要EVAL I(這只是i/100,你已經evali來自用戶的輸入),嘗試簡單地把I=i/100這樣:

def main(): 
    p=eval(input("Enter in the present value of the account: ")) 
    i=eval(input("Enter in the monthly interest rate(%): ")) 
    I=i/100 #simply put this 
    t=eval(input("Enter the number of months that that the money will be in the account: ")) 

    print(futureValue(p, I, t),"Is the future value of your account!") 

def futureValue(p, I, t): 
    return p*((1 + I) ** t) 

main() 

你應該得到你的未來價值

+0

這裏的重要變化並不是去除'eval',而是使用真正的分割('/')來代替floor division('//');當輸入在0-99範圍內時,後者在除以100時總是會產生0,前者將如你所期望的那樣產生0.0-0.99。 'eval'是_evil_,但它不是這裏的罪魁禍首。 – ShadowRanger

+0

是的,當您發佈您的評論時,我正在輸入更新。 :) – Ian

+1

優秀。 Upvoted。 – ShadowRanger