2015-09-24 32 views
0

我想要求用戶輸入數字n,然後打印小於n的所有方塊。例如,如果n = 100,我想它打印0,1,4,9,16,25,36,49,64,81這個while循環有什麼問題? - Python

我做了以下:

n = float(input("Please enter a positive number: ")) 

square = 0.0 

while square < n: 
    square = square + 1 
    print(square * square) 

但那麼如果我執行它,並輸入n = 100,這將打印所有廣場高達1000.我在這裏做錯了什麼?

回答

2

你循環從0到n,然後打印數的平方。 100 * 100爲10000

重命名square變量;它並不準確地反映你正在計算的數據,它是根目錄,而不是平方值。實際上,它只是直線式計數器,每步增加1。然後測試,如果計數器的平方小於n

root = 0.0 
while root * root < n: 
    root = root + 1 
    print(root * root) 

如果您必須存儲的廣場上,就實際存儲的廣場上,不是根:

root = square = 0.0 
while square < n: 
    root = root + 1 
    square = root * root 
    print(square) 

接下來,移動增加print()後,如果您預計81是最後的數字印刷:

root = 0.0 
while root * root < n: 
    print(root * root) 
    root = root + 1 

這可確保您打印剛剛測試的數字的平方,而不是下一個根。

+0

我明白了,謝謝。我嘗試使用你開發的第一個代碼,但是這也打印100,而不是退出81(如果n = 100)。爲什麼是這樣? – Kamil

+0

因爲一旦它計算出新根就會打印根目錄,如果你不想打印'100',從'1.0'開始,先打印然後計算新的根目錄。 –

+0

@Kamil:在*打印後增加根*。你在測試後增加了根,'9 * 9'小於100,然後你加1並打印'10 * 10'。 –