我从以下python函数得到了非常奇怪的输出:
s = "-8.8373347749999997e-08"
def roundNumb(numb, pos):
print("roundNumb()", numb , pos)
ret = ""
if int(numb[pos]) < 5:
ret = numb[:pos]
print("if int(numb[pos]) < 5: ", int(numb[pos]), " ", ret)
else:
if int(numb[pos]) == 9:
ret = roundNumb(numb , pos - 1)
print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)
else:
ret = numb[:(pos-1)] + str(int(numb[(pos-1)]) + 1)
print("else:", ret)
return ret
>>> roundNumb(s, 12)
roundNumb() -8.8373347749999997e-08 12
roundNumb() -8.8373347749999997e-08 11
if int(numb[pos]) < 5: 4 -8.83733477
int(numb[pos]) == 9 9 -8.83733477
'-8.83733477'
正如你所看到的,roundNumb函数被调用了两次,但我真的不明白为什么。它应该在第一个if语句结束:
if int(numb[pos]) < 5:
你调用函数
roundNumb(s, 12) // where numb[pos] = 9
然后函数转到else块 并执行if块
if int(numb[pos]) == 9:
如果您再次调用此函数,则这是此块执行之前的有趣部分
然后functoid执行函数的if块
然后执行此打印功能,然后执行暂停的功能恢复 然后执行这个打印函数
print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)
有关递归的知识对理解这一点非常有帮助
相关问题 更多 >
编程相关推荐