首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >输出数字*2使用while循环

输出数字*2使用while循环
EN

Stack Overflow用户
提问于 2017-03-01 05:05:17
回答 3查看 80关注 0票数 0

我的程序应该接受一个输入,然后将每个数字乘以2,直到达到输入的数字。例如,如果输入的数字是8,它将输出1,2,4,8,16,32,64,128。我的代码停在数字8而不是128。仍未回答

代码语言:javascript
复制
limit = input('Enter a value for limit: ')
limit = int(limit)
ctr = 1
while ctr <= (limit):
    print(ctr, end=' ')
    ctr = ctr * 2
print("limit =", limit )
EN

回答 3

Stack Overflow用户

发布于 2017-03-01 05:09:44

您将ctr乘以2,但将其与8进行比较,因此它从1到2,到4,到8,然后停止。

我不知道为什么要在没有**运算符的情况下这样做,但在这种情况下,您可能必须考虑将计数器(从1到8)和值(从1到128)作为两个独立的变量进行跟踪。

票数 0
EN

Stack Overflow用户

发布于 2017-03-01 05:10:14

再看一下您的while条件:您的循环将一直运行,直到您的产品到达用户的输入。在你的示例中,limit将被设置为8,当ctr达到8时,循环将结束。在这里,我将向你的代码添加一些注释,也许你可以看到你遇到的问题在哪里:

代码语言:javascript
复制
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循环:

代码语言:javascript
复制
for i in range(limit):
    ctr *= 2
票数 0
EN

Stack Overflow用户

发布于 2017-03-01 05:20:50

您的while循环在达到8时停止,正如您的条件中所给出的。

代码语言:javascript
复制
while ctr <=(limit)

您可以通过使用以下代码来简单地实现此结果。

代码语言:javascript
复制
l = int(input())
n = 1
while l>0:
    print(n)
    n *= 2
    l -= 1

我希望这能回答你的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42518707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档