2016-04-05 33 views
0

幫助!我明天有這個程序,要求它必須具有topLeft拐角的X,Y笛卡爾座標和bottomRight拐角的X,Y笛卡爾座標作爲raw_input。然後打印周邊,區域和這兩個位置。 但是我不能讓raw_input工作。我曾嘗試將其轉換爲整型,分割和多個賦值。具有笛卡爾座標raw_input的類矩形?

topLeft = int(raw_input ('Please enter a coordinate==>')).split() 
bottomRight= int(raw_input ('Please enter a coordinate==>')).split() 
class Rectangle: 
    def __init__(self, topLeft, bottomRight): 
     self.tL = topLeft 
     self.bR = bottomRight 
    def perim(self): 
     return (2 * (self.tL)) + (2 * (self.bR)) 
    def area(self): 
     return (self.tL) * (self.bR) 
    def position(self): 
     return (self.tL, self.bR) 
    def __str__(self): 
     return "Rectangle(%s, %s)" % (self.tL, self.bR) 

r1 = (Rectangle (topLeft,bottomRight)) 
print r1 
print "Perimeter: %s" % r1.perim() 
print "Area: %s" % r1.area() 
print "Position: (%s, %s,)" % r1.position() 

這是我最親密的嘗試,但我仍然得到錯誤:

Traceback (most recent call last): 
    File "C:\Users\Mary\Desktop\Python Programs\Rectangle.py", line 1, in <module> 
    topLeft = int(raw_input ('Please enter a coordinate==>')).split() 
ValueError: invalid literal for int() with base 10: '(5,10)' 

回答

0

感覺如何去上班?你犯了很多錯誤。

tx, ty = raw_input("tx ty: ").split() # the input is "4 5", int("5 4")??? 
bx, by = raw_input("bx by: ").split() 

然後

self.tx = int(tx) 
self.ty = int(ty) 
# and so on ... 
# If you want to work with tuples `(xt,yt)` Make both int first. 

。並且您所有的課程方法都不正確,例如perimeter = 2*(bx-tx) + 2*(ty-by)而不是2*(tx,ty) + 2*(bx,by)。在語義上它沒有意義。

+0

我是初學者,非常感謝您的幫助!我參加並調整了我的課堂教學方法,我將這些方法交給了其他人,但是你的教學更有意義。我沒有意識到我需要在課堂上檢查整數。它現在完美地工作。 –

+0

處理座標的更好方法是使用'collections.namedtuple',它們是鬆散的微小* class *工廠,使它們感覺自然。如果'P'是一個名爲tuple class的點,則可以執行'top = P(x = xt,y = yt)'和'top.x top.y'。它看起來很自然。 –

相關問題