这是我得到的所有进一步
import math
num_to_convert = int(input("Please enter any intger from 1 and 100:"))
while num_to_convert < 1 or num_to_convert > 100:
num_to_convert = int(input("Sorry that's not an integer from 1 to 100, try again:"))
else:
print("I'm lost!")
我发现了这个,但我不明白是怎么回事。也许解释一下这是怎么回事会有帮助。
def decimalToBinary(n):
if(n > 1):
# divide with integral result
# (discard remainder)
decimalToBinary(n//2)
print(n%2, end=' ')
似乎你想转换一个整数,而不是一个十进制的二进制从你的代码,我会写
while True:
try:
value1=input("Integer you want to convert to binary: ")
binaryvalue=(bin(int(value1)))
print (binaryvalue[2:])
except:
print("I did not understand that")
pass
Valuetoconvert=int(input("Number to convert: "))
u = format(Valuetoconvert, "08b")
print(u)
Try this then
见下:
def toBin(n):
if n < 2:
return str(n)
else:
if n % 2 == 0:
return toBin(n//2) + "0"
else:
return toBin(n//2) + "1"
解释:
这是我的解决方案,工作原理与你的相似。我希望你们知道什么是递归否则这就很难理解了。无论如何,算法是将数字反复除以2,直到数字小于2,因为这样你就马上得到了答案(基本情况)。
当当前数大于2时,检查是否大于2能被2整除。如果是偶数,则在字符串后面加一个0,否则就加一个1。你可以在纸上试一试,以便更好地理解它。