[英]Python fills string with unnessecary characters
In this Python code, I have the following problem. 在此Python代码中,我遇到以下问题。 When the result is displayed, I get a bunch of zeros in the result (see below) - otherwise, the result is correct (the ending numbers of the string).
当显示结果时,我在结果中得到一堆零(请参见下文)-否则,结果是正确的(字符串的结尾数字)。 Can anyone spot the error?
谁能发现错误?
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()
This is the result if I type "2" 这是我输入“ 2”时的结果
The binary notation is:
二进制符号是:
Change 更改
decNumber = float(input("Enter a positive number: "))
to 至
decNumber = int(input("Enter a positive number: "))
And use integer division. 并使用整数除法。 Instead of
代替
dec = dec / 2
use 采用
dec = dec // 2
with these changes, I get the following output 经过这些更改,我得到以下输出
The binary notation is: 10
@Ragnar, before everything I should mention that your code is wrong. @Ragnar,在一切之前,我应该提到您的代码是错误的。 I tried to convert 12 and 41 with this code and it failed.
我试图用此代码转换12和41,但失败了。 To get a complete help, I suggest you to see this question .
要获得完整的帮助,建议您查看此问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.