zyj1214 发表于 2020-11-19 20:41:49

递归编写一个十进制转换为二进制的函数

def Dec2Bin(dec):
    result = ''
   
    if dec:
      result = Dec2Bin(dec//2)
      return result + str(dec%2)
    else:
      return result

print(Dec2Bin(62))

下面这两句我不太理解:最好能分解到每一步?谢谢!!
result = Dec2Bin(dec//2)
return result + str(dec%2)

zyj1214 发表于 2020-11-19 21:00:23

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))
      

zyj1214 发表于 2020-11-19 21:02:50

看了其他帖子,,,,理解了

jackz007 发表于 2020-11-19 21:18:03

   先对函数变形,效果一样,但是更容易理解
def Dec2Bin(dec):
    if dec:
      return Dec2Bin(dec // 2) + str(dec % 2)
    else:
      return ''
      下面是递归的全过程:
       Dec2Bin(62) = Dec2Bin(62 // 2) + str(62 % 2) = Dec2Bin(31) + '0'
       Dec2Bin(31) = Dec2Bin(31 // 2) + str(31 % 2) = Dec2Bin(15) + '1'
       Dec2Bin(15) = Dec2Bin(15 // 2) + str(15 % 2) = Dec2Bin( 7) + '1'
       Dec2Bin( 7) = Dec2Bin( 7 // 2) + str( 7 % 2) = Dec2Bin( 3) + '1'
       Dec2Bin( 3) = Dec2Bin( 3 // 2) + str( 3 % 2) = Dec2Bin( 1) + '1'
       Dec2Bin( 1) = Dec2Bin( 1 // 2) + str( 1 % 2) = Dec2Bin( 0) + '1'
       Dec2Bin( 0) = ''
       只要从最下面把 Dec2Bin(0) = '' 带入 Dec2Bin(1),得到 Dec2Bin(1) = '1' , 再把这个结果带入 Dec2Bin(3) 得到 Dec2Bin(3) = '11' 。。。。。。最终带入的结果,Dec2Bin(62) = '111110'
       Dec2Bin(62) = '' + '1' + '1' + '1' + '1' + '1' + '0' = '111110'
页: [1]
查看完整版本: 递归编写一个十进制转换为二进制的函数