Mojoo08 发表于 2020-3-11 09:23:06

编写一个将十进制转换为二进制的函数,要求采用“除2取余”(补脑链接)的方式,结...

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

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

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


我感觉这个代码没问题啊,但是就是打印不出正确的值,请各位大神帮忙看下问题在哪?谢啦谢啦

qiuyouzhi 发表于 2020-3-11 09:26:08

代码得这么写:
def dec2bin(dec):
      temp = []
      result = ''

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

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

print(dec2bin(9))

wuqramy 发表于 2020-3-11 09:38:09

两个问题:
1.第二个循环不是循环result,是循环temp
2.return result那一句缩进错误,应该在循环外面
修改代码如下:
def dec2bin(dec):
      temp = []
      result = ''

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

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

Mojoo08 发表于 2020-3-11 13:49:38

wuqramy 发表于 2020-3-11 09:38
两个问题:
1.第二个循环不是循环result,是循环temp
2.return result那一句缩进错误,应该在循环外面


谢谢 wuqramy!经过你的指点,我发现问题了,纠结了一早上! 感谢感谢,手动ღ( ′・ᴗ・` )比心!

Mojoo08 发表于 2020-3-11 13:51:28

qiuyouzhi 发表于 2020-3-11 09:26
代码得这么写:

感谢大神,手动ღ( ′・ᴗ・` )比心!
页: [1]
查看完整版本: 编写一个将十进制转换为二进制的函数,要求采用“除2取余”(补脑链接)的方式,结...