你是我的小可爱 发表于 2020-2-21 15:56:17

程序解释

def Dec2Bin(dec):
    temp = []
    result = ''

    while dec:
      quo = dec % 2
      dec = dec // 2
      temp.append(quo)

    while temp:
      result += str(temp.pop())

    return result

print(Dec2Bin(62))
这段代码中:while temp:
      result += str(temp.pop())
这个是啥意思啊,请大神指教!

xiaofan1228 发表于 2020-2-21 16:12:46

temp在前面被你定义成了字符串,结合上面 while dec: 可以看出 temp是一个把十进制转换成二进制以后形成的字符串列表,比如 dec = 5 , 此时temp = ["1", ",0", “1”] ,所以while temp 返回值是1。 pop()函数默认从最后一位开始输出,结果叠加到字符串result上,直到 temp变为[] ,返回的result以字符串的形式。

你是我的小可爱 发表于 2020-2-21 16:19:45

懂了,万分感谢!
页: [1]
查看完整版本: 程序解释