求助一小程序
def Dec2Bin(dec):result = ''
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2)
else:
return result
print(Dec2Bin(62))
不是特别明白怎么运行和储存的,求大佬解释 不用重复发帖。。。
我只好再copy一份回答
先明白两个主要的while循环是做什么的:
while dec:#这个循环用来找出每一位数0或1
quo = dec % 2
dec = dec // 2
temp.append(quo)
while temp:#逆序输出即得到结果
result += str(temp.pop())
然后去搞清楚十进制转换为二进制的数学过程,参考:
http://bbs.fishc.com/thread-67123-1-1.html
最后举个例子,看看上面过程是怎么实现的:
比如传入15
那么进入函数后,第一个循环过程如下:
quo == 13%2==1,dec == dec//2 == 6,temp ==
quo == 6%2==0,dec == dec//2 == 3,temp ==
quo == 3%2==1,dec == dec//2 == 1,temp ==
quo == 1%2==1,dec == dec//2 == 0,temp ==
退出循环
进入下一个循环,将temp逆序赋值给result = 1101
所以15的二进制表示为1101 BngThea 发表于 2018-1-31 15:50
不用重复发帖。。。
我只好再copy一份回答
先明白两个主要的while循环是做什么的:
谢谢,你发的解释看懂了,还想问一下:
上面我发的 result = '',这个字符串是怎么存储递归对象和余数? 怎么进行递归的?
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2) heimanbacll 发表于 2018-1-31 16:18
谢谢,你发的解释看懂了,还想问一下:
上面我发的 result = '',这个字符串是怎么存储递归对象和 ...
搞清楚了二进制的基本原理,要理解递归就很容易了
当然,前提是你知道递归的要点:
1 会在调用自身的时候暂停其后面的所有代码
2 在返回的时候接着执行器后面所有的代码
页:
[1]