繁体   English   中英

我如何用while循环解决这个问题

[英]How do I solve this problem with while loop

c0=int(input("enter a number here"))

题:

  1. 取任何非负非零整数并将其命名为 c0;
  2. 如果是偶数,则将新的 c0 评估为 c0 ÷ 2;
  3. 否则,如果是奇数,则将新的 c0 计算为 3 × c0 + 1;
  4. 如果 c0 ≠ 1,则跳到第 2 点
  5. 编写一个程序,读取一个自然数并执行上述步骤,只要 c0 保持不为 1
  6. 我们还希望您计算实现目标所需的步骤。 您的代码也应该输出 c0 的所有中间值。

我的代码:

c01=c0%2
c02=3*c0+1
while c0!=1:
    if c01==0:
        print(c01)
    else:
        print(c02)
    c0+=1
print("total number steps",)

样本输入:16

预期输出:

8
4
2
1
steps = 4
while True:
    c0 = int(input("Enter a Number Here: "))
    if c0 > 0:
        break
    else:
        continue

count = 0

while c0 != 1:
    if c0 % 2 == 0:
        c0 = c0 / 2
        print("{} ".format(int(c0)))
    else:
        c0 = 3 * c0 + 1
        print("{} ".format(int(c0)))
    count += 1

print("Steps: {}".format(count))

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM