我正在尝试实现基本的递归函数,一旦高参数不大于低参数,该函数便应终止。
import time
def whileBlock(low, high):
print("New low value:",low,"------","New high value:",high)
while low < high:
mid = (low + high)//2
print("Low:",low,"Mid:",mid,"high:",high)
time.sleep(2)
whileBlock(low, mid)
whileBlock(0,10)
计算出的中间值被传递给递归函数。 对于前4个迭代,代码按预期运行。从第5次迭代开始,尽管high等于0(与low相同),但是条件没有终止并且陷入无限循环。
当条件上方的print语句显示为0时,为什么while循环仍然变得高至1,我无法理解。
代码输出
whileBlock(0,10)
New low value: 0 ------ New high value: 10
Low: 0 Mid: 5 high: 10
New low value: 0 ------ New high value: 5
Low: 0 Mid: 2 high: 5
New low value: 0 ------ New high value: 2
Low: 0 Mid: 1 high: 2
New low value: 0 ------ New high value: 1
Low: 0 Mid: 0 high: 1
New low value: 0 ------ New high value: 0
Low: 0 Mid: 0 high: 1
New low value: 0 ------ New high value: 0
Low: 0 Mid: 0 high: 1
New low value: 0 ------ New high value: 0
Low: 0 Mid: 0 high: 1
New low value: 0 ------ New high value: 0
Low: 0 Mid: 0 high: 1