我的程序应该接受一个输入,然后将每个数字乘以2,直到达到输入的数字。例如,如果输入的数字是8,它将输出1,2,4,8,16,32,64,128。我的代码停在数字8而不是128。仍未回答
limit = input('Enter a value for limit: ')
limit = int(limit)
ctr = 1
while ctr <= (limit):
print(ctr, end=' ')
ctr = ctr * 2
print("limit =", limit )发布于 2017-03-01 05:09:44
您将ctr乘以2,但将其与8进行比较,因此它从1到2,到4,到8,然后停止。
我不知道为什么要在没有**运算符的情况下这样做,但在这种情况下,您可能必须考虑将计数器(从1到8)和值(从1到128)作为两个独立的变量进行跟踪。
发布于 2017-03-01 05:10:14
再看一下您的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循环:
for i in range(limit):
ctr *= 2发布于 2017-03-01 05:20:50
您的while循环在达到8时停止,正如您的条件中所给出的。
while ctr <=(limit)您可以通过使用以下代码来简单地实现此结果。
l = int(input())
n = 1
while l>0:
print(n)
n *= 2
l -= 1我希望这能回答你的问题。
https://stackoverflow.com/questions/42518707
复制相似问题