我目前正在编写一个小脚本,旨在查找出租车车号。只有一个小问题,for循环不会增加变量x,并且会永远循环。我将粘贴以下代码的相关部分:
n = int(10)
counter = int(0)
m = int(m)
x = int(1)
y = int(n**(1/3))
cheatsheet = []
while counter in range(0,m):
for x in range(1,y):
if x**3 + y**3 < n:
print('less than')
print(x,y,n)
continue
elif x**3 + y**3 > n:
print('greater than')
y -= 1
continue
elif x > y:
if n in cheatsheet:
print('counting')
counter = counter+1
#checking if n occurs in the list, if so it will add 1 to the counter so that the program will know when to stop
n = n + 1
y = int(n**(1/3))
x = 1
print('break1')
#resetting values and bumping n so that it will continue the quest to find 'em all
break
else:
if x and y == 1:
#this is an error correction for low n values, i mean really low it might be redundant by now
n = n + 1
y = int(n**(1/3))
x = 1
print('break2')
break
cheatsheet.append((n,x,y))
print(cheatsheet)这将在终端窗口中产生以下结果:image
请注意,我自己杀死了进程,但程序没有。正如您可以看出的,该脚本只是循环并打印‘小于’和x,y,n的值。
非常感谢您的帮助!
编辑:变量m由用户提供,但不包括在这段代码中。
发布于 2016-09-06 17:43:05
这有一些问题,我不愿意发布函数代码,但我会指出其中的一些问题。
对于初学者:
n = int(10)不是必需的,不是错误而是多余的。使用具有相同效果的n = 10。
然后:
while counter in range(0,m):将始终计算为True。m从来没有修改过,所以成员测试总是成功的,也许你需要重新评估你的循环。
for x in range(1,y):这将始终为x赋值1。y根据您的算术计算为2 (整数四舍五入浮点到底数,即int(2.9) -> 2),因此要么使用math.ceil,要么在y中加1。
除此之外,你总是在循环中重新分配变量名,这是令人困惑的,并可能导致意想不到的行为。
https://stackoverflow.com/questions/39344596
复制相似问题