2014-07-15 44 views
-4

我剛開始編寫代碼,我試圖編寫一個簡單的程序來添加向量。到目前爲止,我有如何使輸入數值

VectorAx= input("What is the x component of Vector A?") 
VectorAy= input("What is the y component of Vector A?") 
VectorBx= input("What is the x component of Vector B?") 
VectorBy= input("What is the y component of Vector B?") 


VectorC= "[%s,%s]" % (VectorAx + VectorBx, VectorAy+VectorBy) 
print (VectorC) 

當我運行腳本一切正常,但輸入不被視爲數字。 例如,如果VectorAx=1,VectorAy=6, VectorBx=3VectorBy=2,VectorC應該是[4,8],但是反而它顯示爲[13,62]

回答

2

input總是返回一個字符串對象。如果你想輸入爲數字,你需要將它們轉換成數字與任何intfloat

VectorAx= int(input("What is the x component of Vector A?")) 
VectorAy= int(input("What is the y component of Vector A?")) 
VectorBx= int(input("What is the x component of Vector B?")) 
VectorBy= int(input("What is the y component of Vector B?")) 

演示:

>>> inp1 = int(input(":")) 
:1 
>>> inp2 = int(input(":")) 
:2 
>>> inp1 + inp2 
3 
>>> 
1

投下你的向量花車(如果你打算在具有小數)或整數(如果它們總是簡單的整數),然後添加。

現在他們正在作爲字符串被採取。

因此"1"+"3" == "13"

int("1") + int("3") == 4

因此:

VectorAx= int(input("What is the x component of Vector A?")) 
VectorAy= int(input("What is the y component of Vector A?")) 
VectorBx= int(input("What is the x component of Vector B?")) 
VectorBy= int(input("What is the y component of Vector B?")) 


VectorC= "[%s,%s]" % (VectorAx + VectorBx, VectorAy+VectorBy) 

,或者你可以直接在這裏投:

VectorC= "[%s,%s]" % (int(VectorAx) + int(VectorBx), int(VectorAy)+ int(VectorBy)) 
1

您需要使用內置int()功能。

根據documentation,此函數將「將數字或字符串x轉換爲整數,如果未給出任何參數,則返回0」。

這將傳遞給它的輸入轉換爲整數。

因此,生成的代碼應該是:

VectorAx = int(input("What is the x component of Vector A?")) 
VectorAy = int(input("What is the y component of Vector A?")) 
VectorBx = int(input("What is the x component of Vector B?")) 
VectorBy = int(input("What is the y component of Vector B?")) 
+3

哎呀!不要在用戶輸入中使用'eval()'!如果有的話,如果有必要,使用'ast.literal_eval()',但不能用於簡單的數字。 –

+0

正確,但我的鏈接進入了'int'內置函數。 – okoboko

+0

正確,但您正在查看'int'(類型)而不是'int'(函數),它是一個內置函數,根據https://docs.python.org/2/library/functions.html #int。 – okoboko