【问题标题】:Ouput numbers *2 using while loop使用 while 循环输出数字 *2
【发布时间】:2017-03-02 04:07:26
【问题描述】:

我的程序应该接受一个输入,然后将每个数字乘以 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 )

【问题讨论】:

  • 我是全新的,我也想在没有 ** 运算符的情况下这样做
  • 好吧,想想你的情况:while ctr &lt;=(limit),它完全按照你的指示去做。无论如何,你真的应该为此使用for 循环。
  • 你把值和计数器搞混了。
  • powers= (limit)*2 的意义何在?它甚至没有使用
  • @juanpa.arrivillaga 我需要在 while 循环中执行此操作,即使 for 循环是更好的执行方式

标签: python python-3.x while-loop


【解决方案1】:

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

我不确定为什么要在没有 ** 运算符的情况下执行此操作,但在这种情况下,您可能需要考虑跟踪计数器(从 1 到 8)和值(从 1 到 128)作为两个独立的变量。

【讨论】:

  • 我对你添加第二个变量的意思感到困惑
【解决方案2】:

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

while ctr <=(limit)

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

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

我希望这能回答问题。

【讨论】:

    【解决方案3】:

    再次查看您的while 条件:您的循环一直运行,直到您的产品到达用户的输入。在您的示例中,limit 将设置为 8,并且您的循环将在 ctr 达到 8 时结束。在这里,我将在您的代码中添加一些 cmets,也许您可​​以看到您遇到的问题是:

    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
    

    【讨论】:

    • 我对你添加另一个变量的意思感到困惑
    • 一个变量计算循环运行的次数,当它达到某个值时停止循环。 (在你的情况下,limit)。当您将结果乘以 2 时,另一个值会保存您的结果。它的要点是,现在,一旦您达到用户输入的数字,您的循环就会停止,而不是在运行多次之后。
    • 您能看看我对代码所做的编辑吗?我陷入了无限循环
    • @BigMan_13 看起来你已经解决了你的无限循环问题,但是看看我对我的答案所做的编辑,看看这是否有助于你找出错误所在。
    猜你喜欢
    • 2013-09-28
    • 2012-01-02
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2021-11-02
    • 2017-03-16
    相关资源
    最近更新 更多