2017-02-28 88 views
0

我的程序應該接受一個輸入,然後將每個數字乘以2直到達到輸入數字。例如,如果輸入的數字是8,則輸出1,2,4,8,16,32,64,128。我的代碼在8號被停止,而不是去128懸而未決STILL使用while循環輸出數字* 2

limit = input('Enter a value for limit: ') 
limit = int(limit) 
ctr = 1 
while ctr <= (limit): 
    print(ctr, end=' ') 
    ctr = ctr * 2 
print("limit =", limit) 
+0

我是這個品牌的新手,我也想這樣做,而不需要**運營商 –

+0

好吧,想想你的情況:'while ctr <=(limit)',它完全按照你所說的去做。無論如何,你應該真的使用'for'循環。 –

+1

你在混合價值和計數器。 –

回答

0

你乘以2 ctr,但相比8,所以從1,2,4,以8,然後停下來。

我不確定爲什麼你想要這樣做沒有**運算符,但在這種情況下,你可能不得不考慮跟蹤計數器(從1到8)和值(從1到128 )作爲兩個單獨的變量。

+0

我對你的意思添加第二個變量感到困惑 –

0

再次看看您的while條件:您的循環運行,直到您的產品達到用戶的輸入。在你的例子中,limit將設置爲8,你的循環將在ctr達到8時結束。在這裏,我將添加一些註釋到你的代碼,也許你可以看到你遇到的問題是:

limit = input('Enter a value for limit: ') 
limit = int(limit) # Getting input from the user. If the user enters n, 
        # the program should output powers of 2 up to 2^n 
ctr = 1   # Initializing the variable holding the powers of 2 
while ctr <= (limit): # While the power of 2 is less than n (This line is 
         # where your problem is. Your loop ends when the 
         # power of 2 reaches n, not 2^n) 
    print(ctr, end=' ') # Print the power of 2 
    ctr = ctr * 2  # Double the power of 2 to get the next one 
print("limit =", limit) # Print the number the user put in 

爲了解決這個問題,要麼使用一個獨立的變量爲你的循環計數器和你的產品,或者更好的使用for循環:當它達到8,

for i in range(limit): 
    ctr *= 2 
+0

我對你的意思加上另一個變量感到困惑 –

+0

一個變量計算循環運行的次數,當你停止循環時它達到了一定的價值。 (在你的情況下,'limit')。另一個值可以在你將結果乘以2的情況下保持你的結果。它的要點在於,當你達到用戶輸入的數字時,你的循環就會停止,而不是在運行多次之後停止。 – Kirill

+0

你可以看看編輯我做我的代碼?我被困在一個無限循環中 –

0

while循環停止爲您的病情給予。

while ctr <=(limit) 

你可以簡單地實現通過下面的代碼的結果。

l = int(input()) 
n = 1 
while l>0: 
    print(n) 
    n *= 2 
    l -= 1 

我希望這會回答查詢。