我正在尝试用 Python 编写一段代码,显示使用简单算法从任意数字达到 1 所需的步骤数。这是我的代码:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+' Steps needed: '+count)
它卡住了,没有显示错误消息,我不知道为什么会发生这种情况。
最佳答案
1) 您错误地调用了 range()
。
您的代码:for n in range(max - min):
生成从 0
开始并以值 max-min< 结束的数字范围
。相反,您需要从 min
开始到 max
结束的数字范围。
试试这个:
for n in range(min, max):
2) 您正在执行浮点除法,但该程序应该仅使用整数除法。试试这个:
num = num // 2
3) 您正在错误的循环上下文中更新 count
变量。尝试将其缩进一站。
4)您的最后一行可能是:
print('Number: '+str(n)+' Steps needed: '+str(count))
程序:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+' Steps needed: '+str(count))
结果:
Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5
Number: 3 Steps needed: 7
Number: 4 Steps needed: 2
Number: 5 Steps needed: 5
关于Python 循环卡住且没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38468670/