当我尝试将十进制转换为二进制时,代码执行时没有错误,但结果为“无”。
有时它只是不显示任何东西。
我觉得有一些逻辑错误,任何人都可以帮助我纠正错误吗?
Code :
def bin_no():
global rem
n = int(input("Enter Number : ")) #Taking a Decimal Num
while n >=1 : #Initiating a Loop to Convert Decimal To Binary using the (Divide By 2 Method).
rem = []
n = n//2
rem.append(n%2)
if n !>=1: #Going back to the loop if input is invalid.
print("Please enter a Valid Number")
bin_no()
print("Binary Number : ", rem.reverse()) #Printing the result (the binary no. was stored in reverse order.)
bin_no()
以下是您的代码的一些问题:
-
rem = []
位于 while 循环内,因此在每个循环迭代中rem
会变成[]
最后它只会存储最后一位。
-
的顺序//
and %
操作错误,//
首先会截断数据%
总会产生0
。您需要颠倒这些操作的顺序。
-
reverse
is a list
就地反转并返回的方法None
。这就是为什么你的代码总是打印None
。所以,你需要使用rem.reverse()
在最后一个之前print
线条和打印rem
通常情况下。
进行这些更改后,您的代码将如下所示:
def bin_no():
global rem
n = int(input("Enter Number : ")) #Taking a Decimal Num
rem = []
while n >=1 : #Initiating a Loop to Convert Decimal To Binary using the (Divide By 2 Method).
rem.append(n%2)
n = n//2
if n >=1: #Going back to the loop if input is invalid.
print("Please enter a Valid Number")
bin_no()
rem.reverse()
print("Binary Number : ", rem) #Printing the result (the binary no. was stored in reverse order.)
bin_no()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)