理论上,这段代码应该能够将十进制转换为二进制,但不断返回一个回溯错误。
decimal = int(input("Enter number: "))
string1 = ""
while decimal>0:
bit = decimal%2
quoteint = decimal/2
str1.append(bit)# append the bit to the left of any previous bits
number = quoteint
print (str1)
或
decimal = int(input("Enter number: "))
string1 = ""
while decimal>0:
bit = decimal%2
quoteint = decimal/2
str1 = str1 + bit # append the bit to the left of any previous bits
number = quoteint
print (str1)
有人可以解释为什么它不起作用,如果有机会解决它?我可能完全错了,因为我要离开这个:http://chortle.ccsu.edu/assemblytutorial/zAppendixH/appH_4.html
我们的想法是使用python中的简单函数创建一个十进制到二进制转换器。
感谢。
答案 0 :(得分:0)
这可能会有所帮助。我创建了一个名为divi的函数,当除以2时会返回数字的余数。
def divi(y):
"""This function returns the remainder of a number when divided by 2 """
mod=y%2
return mod
然后我用它来创建剩余部分的列表。这是通过重复进行num // 2模除法直到num达到1来完成的。
num=int(input("enter a decimal number "))
b=num # Assigning the value of num to a variable b for
later reference
lst=[] # Defining a list
while(num>=1):
lst.append(divi(num)) #making a list having all the
remainders when num is divided by 2 until num approaches 1
num=num//2
然后我反转列表以获取二进制数。
v=list(reversed(lst)) #reversing the list above to get
the binary form
str1=''.join(str(e) for e in v) # converting the list to a
string and then joining them together
print("The binary form of {} is {} ".format(b,str1))