2014-04-03 53 views
0

所以我剛剛開始編寫Python代碼,並且我已經分配了一個項目來使用Monte Carlo算法估計pi的值。我已經有了一些概念,但現在我需要打印一個正方形並在其上放置複選標記。廣場需要由用戶設置的大小來定義。製作一個正方形

我設法讓方使用下面的代碼打印:

import random 
#defines the size of the square 
squareSize = raw_input("Enter a square size:") 
#defines the width of the square 
print "#" * (int(squareSize)+2) 
#defines the length of the square. 
for i in range(0,int(squareSize)): 

    print "#", " " * (int(squareSize)-2), "#" 

print "#" * (int(squareSize)+2) 

無論出於何種原因,當我補充一下:

#determines the x value of a point to display 
x = random.uniform(-1*(squareSize),squareSize) 

或其他任何可創建與食堂的變量「平方尺寸」我收到以下內容:

Traceback (most recent call last): 
    File "<stdin>", line 6, in <module> 
    File "/lib/python2.7/random.py", line 357, in uniform 
    return a + (b-a) * self.random() 
TypeError: unsupported operand type(s) for -: 'str' and 'str' 

我會很感激任何幫助,我可以ge用這個,我確定這是愚蠢的,我只是俯視,但我不能爲我的生活弄清楚。

謝謝,

Alex。

+1

squareSize變量(更改類型),你在random.uniform忘了「INT」 :'random.uniform(-1 * int(squareize),int(squaresize))。但是@alecxe建議,你應該只做一次這個操作。 – fredtantini

回答

3

問題是squareSizestr類型。 random.uniform等待int類型的參數。

您可以通過簡單地有固定的:

x = random.uniform(-1*(int(squareSize)),int(squareSize)) 

但是,更好的投squareSizeint一旦開頭:

squareSize = int(raw_input("Enter a square size:")) 

的代碼最終應該是這樣的:

import random 

squareSize = int(raw_input("Enter a square size:")) 

print "#" * (squareSize + 2) 
for i in range(0,squareSize): 
    print "#", " " * (squareSize) - 2, "#" 
print "#" * (squareSize + 2) 

x = random.uniform(-1 * squareSize, squareSize) 

希望有幫助。

+0

感謝您的幫助,併爲最近的回覆感到抱歉。完美工作。 – alexniu149

1

raw_input函數返回字符串(str),而不是一個整數(int

由於squareSize是一個字符串,則不能在其上執行的-操作。 因爲這不是你想要做的。您想要對兩個整數執行減法(或功能random)。

所以,爲了這個目的,你可以施放通過轉換由raw_input返回的字符串爲int

#defines the size of the square 
squareSize = raw_input("Enter a square size:")