简体   繁体   English

我如何使它可以循环?

[英]How do I make it so it can loop?

I need to test whether n is a multiple of 2 and then divide the number by 2. If the number isn't a multiple of 2, then I have to do 3*n+2.我需要测试n是否是2的倍数,然后将数字除以2。如果数字不是2的倍数,那么我必须做3 * n + 2。

How do I make it loop so I can get the following: 12, 6, 3, 10, 5, 16, 8, 4, 2, 1?如何使其循环,以便获得以下信息:12、6、3、10、5、16、8、4、2、1?

Here's my current code:这是我当前的代码:

n=12
while n!=0:
    if n%2==0:
        print (n)
    n=n/2
    if n!=n%2:
        if n !=1:
            n = 3*n+2
    else:
        break
print(n)

First of all your formula of 3*n + 2 will lead to infinite loop.首先,您的3*n + 2公式将导致无限循环。 According your sample output, it needs to be 3*n + 1 .根据您的样品 output,它需要是3*n + 1

n = 12
while n >= 1:
    print(n, end=' ')

    if n == 1:
        break

    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1

First note is that it is 3*n+1, second one is that you have to write n=n/2 in your first if.第一个注意是它是 3*n+1,第二个是你必须在你的第一个 if 中写 n=n/2。

Overall this code is what you want:总的来说,这段代码就是你想要的:

n = 12
while n != 0:
  if n % 2 == 0:
    print(n, end=' ')
    n = n / 2
    
  elif n % 2 != 0:
    if n != 1:
        print(n, end=' ')
        n = 3 * n + 1   
    else:
        print(1)
        break

Or this:或这个:

n = 12
while n > 1:
  if n % 2 == 0:
    print(n, end=' ')
    n = n / 2

  elif n % 2 != 0:
    if n != 1:
        print(n, end=' ')
        n = 3 * n + 1   
    else:
        print(1)

Good luck祝你好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 事件可以执行命令吗? 如果是这样,我怎样才能让我的人这样做? - Can an event execute a command? If so, how can I make my one do so? 我该如何制作它,以便每个循环每次出现只打印一次? - How do I make it so it only prints once per occurrence per loop? 当条件为假时,如何使while循环立即终止? - How do I make it so a while loop terminates immediately when the condition is false? 我知道我将此for循环写错了,那么如何正确编写它才能接受多个字母? - I know I am writing this for loop wrong, so how do I write it correctly so that it can accept multiple letters? 如何使它成为for循环? - How do I make this into a for loop? 我该如何进行循环,以使该点每次转动都累加到“用户”或“比较”中? - How can I make a loop so that the point gets added up to “user” or “comp” at every turn? 我怎样才能使循环不断重复,直到列表中的所有元素都得到回答? - How can I make it so that the loop keeps repeating until a all the elements in the list are answered? 我如何制作用户配置文件,以便我输入姓名、邮件等,然后保存,以便我可以登录 - How do i make a user profile so that i will input the name, mail etc. and then it saves, so i can login 我如何使用 for 循环,以便在它运行我的第一个列表之后,它将继续使用我的第二个 for 循环和另一个列表 - How do i make use for loop so that after it has ran my first list then it will continue on with my second for loop with another list 如何将索引变成变量以便我可以将它用于 tkinter? - How do i make an index into a variable so i can use it for tkinter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM