decimal = int(input("Enter the Decimal value :"))
def d_b(decimal,binary):
# function to convert decimal to binary
binary = binary + str(decimal % 2)
if decimal > 1:
d_b(decimal//2,binary)
else :
print (binary)
return (binary)
print ("Decimal to Binary : ", d_b(decimal,binary = ''))
输入34的输出:
010001
十进制转换为二进制:无
该函数会打印答案,但不会返回答案,然后开始返回到函数,并开始从字符串中逐个删除字符,最后不返回任何字符,而是返回二进制字符串。
正确的代码:
decimal = int(input("Enter the Decimal value :"))
def d_b(decimal,binary):
# function to convert decimal to binary
if decimal > 0:
binary = d_b(int(decimal)//2,binary)
binary = binary + str(decimal % 2)
return (binary)
print ("Decimal to Binary :",d_b(decimal,binary = ''))
答案 0 :(得分:0)
尝试一下,不客气:
def d_b(decimal,binary):
# function to convert decimal to binary
binary = binary + str(decimal % 2)
if decimal > 1:
binary = d_b(int(decimal/2), binary) # <-- this is the line you should change
return binary
或什至更短的三元运算符:
return decimal > 1 ? d_b(int(decimal/2), binary): binary