使用递归编写一个十进制转换为二进制的函数
def Dec2Bin(dec):result = ''
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2)
else:
return result
print(Dec2Bin(62))
代码看不懂请大神帮忙注释一下真心的谢谢 为了讨论方便,先简化程序代码
def Dec2Bin(dec):
result = ''
if dec:
result = Dec2Bin(dec // 2) + str(dec % 2)
return result
递归就是函数自己调用自己的行为,递归函数一般都有两个分支,一个有递归,另一个无递归,一开始都有递归,当执行到无递归分支的时候,递归就到底了。以底为界,递归分为进入过程和退出过程。就本例而言,递归的进入过程到 Dec2Bin(0) 也就是 dec = 0 的候到底,并开始有了确切的返回值,不过,这个返回值只是一个空字符串 '',然后,开始了逐级退出的过程,并依次确定了各自的返回值。最后返回字符串 '111110',其实就是从递归到底开始,把各级的递归中的 dec % 2 转化成字符串然后按顺序加在一起得到。
Dec2Bin(62) = Dec2Bin(31) + '0' # Dec2Bin(31) + '0' = Dec2Bin(62)
= Dec2Bin(15) + '1' + '0' # Dec2Bin(15) + '1' = Dec2Bin(31)
= Dec2Bin( 7) + '1' + '1' + '0' # Dec2Bin( 7) + '1' = Dec2Bin(15)
= Dec2Bin( 3) + '1' + '1' + '1' + '0' # Dec2Bin( 3) + '1' = Dec2Bin( 7)
= Dec2Bin( 1) + '1' + '1' + '1' + '1' + '0' # Dec2Bin( 1) + '1' = Dec2Bin( 3)
= Dec2Bin( 0) + '1' + '1' + '1' + '1' + '1' + '0' # Dec2Bin( 0) + '1' = Dec2Bin( 1)
= '' + '1' + '1' + '1' + '1' + '1' + '0' def Dec2Bin(dec):
result = ''
if dec: #如果dec不等于0
result = Dec2Bin(dec//2)
return result + str(dec%2)
'''
result + str(dec%2)=Dec2Bin(62//2) + str(62%2)
=Dec2Bin(31) + str(62%2)
=Dec2Bin(31//2) +str(31%2) + str(62%2)
=Dec2Bin(15) +str(31%2) + str(62%2)
=Dec2Bin(15//2) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(7) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(7//2) + str(7%2) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(3) + str(7%2) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(3//2) + str(3%2) + str(7%2) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(1) + str(3%2) + str(7%2) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(1//2)+ str(1%2) + str(3%2) + str(7%2) + str(15%2) +str(31%2) + str(62%2)
=Dec2Bin(0)+ str(1%2) + str(3%2) + str(7%2) + str(15%2) +str(31%2) + str(62%2)
='' +'1'+'1'+'1'+'1'+'1'+'0'
='111110'
'''
else:
return result
print(Dec2Bin(62))
jackz007 发表于 2020-2-28 22:50
为了讨论方便,先简化程序代码
递归就是函数自己调用自己的行为,递归函数一般都有两个分支, ...
谢谢你我明白了谢谢
页:
[1]