在这个Python代码中,我有以下问题。显示结果时,我在结果中得到一堆零(见下文) - 否则,结果是正确的(字符串的结束数字)。有人能发现错误吗?
def menu():
binNumber = ''
decNumber = float(input("Enter a positive number: "))
decNumber, binNumber = decimalToBinary(decNumber, binNumber)
printResult(binNumber)
def decimalToBinary(dec, bin):
while dec != 0:
remain = dec % 2
dec = dec / 2
if remain > 0.5:
bin += '1'
else:
bin += '0'
return dec, bin
def printResult(binNumber):
print("The binary notation is:", binNumber[::-1]) # the last part is to reverse the string
menu()
如果我输入“2”
,这就是结果二进制表示法是: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000010
答案 0 :(得分:1)
更改
decNumber = float(input("Enter a positive number: "))
到
decNumber = int(input("Enter a positive number: "))
并使用整数除法。而不是
dec = dec / 2
使用
dec = dec // 2
通过这些更改,我得到以下输出
The binary notation is: 10
答案 1 :(得分:0)
@Ragnar,在我应该提及你的代码错误之前。我尝试使用此代码转换12和41,但它失败了。为了获得完整的帮助,我建议您查看this question。