这道课后习题的答案有点看不懂,求大佬解答一下!谢谢
问题:使用递归编写一个十进制转换为二进制的函数(要求采用“取2取余”的方式,结果与调用bin()一样返回字符串形式)参考答案如下:
def Dec2Bin(dec):
result = ''
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2)
else:
return result
dec = 10
result =‘’
if 当为0时为假,非0即真
result = Dec2Bin(5) result = 101 return 101 + 10 % 2 = 1010最终结果
result =‘’
dec = 5
if 当为0时为假,非0即真
result = Dec2Bin(2) result = 10return 10+ 5 % 2 = 101
result =‘’
dec = 2
if 当为0时为假,非0即真
result = Dec2Bin(1)result = 1return 1 + 2 % 2 = 10
result =‘’
dec = 1
if 当为0时为假,非0即真
result = Dec2Bin(0) result = ''return 0 + 1 % 2= 1
result =‘’
if 当为0时为假,非0即真
else return result
注意这里是result + str(dec%2) 字符串相加 请见:https://fishc.com.cn/forum.php?mod=viewthread&tid=167696&ctid=1730 均昊山 发表于 2020-7-19 02:50
dec = 10
result =‘’
您好!感谢您的解答,我还是有点不懂:
else return result,这条语句执行完后,跳到result = Dec2Bin(dec//2)这条语句,但是他不执行这条语句,就直接跳到下一条语句return result + str(dec%2)了呢?还有就是,else return result之后怎么知道,dec的值?刚学Python很多东西不懂,感谢答主啦! 吴川靓仔学编程 发表于 2020-7-19 12:33
您好!感谢您的解答,我还是有点不懂:
else return result,这条语句执行完后,跳到result = Dec2Bin( ...
else return result 返回‘’ ------- result = Dec2Bin(dec//2) 这里的Dec2Bin(dec//2) 值是‘’
return result + str(dec%2)‘’+ dec%2 这里的dec参数 是来自result = Dec2Bin(1) 吴川靓仔学编程 发表于 2020-7-19 12:33
您好!感谢您的解答,我还是有点不懂:
else return result,这条语句执行完后,跳到result = Dec2Bin( ...
def Dec2Bin(dec):
result = ''
if dec:
print('dec',dec)
result = Dec2Bin(dec//2)
print (result)
print (type(result))
return result + str(dec%2)
else:
print('dec',dec)
return result
a = Dec2Bin('10')
运行看看,配合我凌晨发的,不懂私信我 均昊山 发表于 2020-7-19 12:51
def Dec2Bin(dec):
result = ''
终于懂啦,谢谢大哥,爱你~
页:
[1]