我得在我的编码课上做一份菜单。用户可以在菜单上选择一个数字,并且菜单可以关闭。除了二进制到十进制,我什么都记下来了。我的代码如下所示。你知道吗
base10
是我正在研究的。我只是不知道该怎么做,因为我不得不缺课,他在课堂上又复习了一遍。你知道吗
#Name: Menu
#Input:
#Output:
#Description:
def menu():
while(True):
print("Welcome The Menu")
print("\t 1. Convert Binary to Decimal")
print("\t 2. Convert Decimal to Binary")
opt=input("Input a number or 9 to Quit. ")
if(int(opt)==1):
base10()
elif(int(opt)==2):
base2()
elif(int(opt)=="9"):
break;
else:
print("Invalid Input")
#Name: Reverse
#Input: String s
#Output: String r
#Description: This function takes a string as input and reverses that string
#returning it as output.
def reverse():
r=""
for i in s:
r=i + r
return r
#Name: Base 10
#Input:
#Output:
#Description
def base10():
num=int(input("Enter a binary number:"))
sum=0
for i in range(0,len()):
sum+=(int([i])*(2**i))
print(sum)
#Name: Base 2
#Input: num
#Output: b
#Description: It takes the number from the user and divides it by two. B is the binary number and num is the decimal number.
def base2():
b=""
num=int(input("Enter a decimal number: "))
while(num != 0):
b=str(num % 2) + b
num=num // 2
int(num == 10)
print(b)
menu()
预期的结果是我在菜单中输入一个数字,选择二进制到十进制或十进制到二进制。然后我应该能够输入base2
和base10
的数字,并得到相反的结果。(我不能用垃圾箱!)你知道吗
(正)整数的二进制表示可以看作是加权和。你知道吗
考虑
1011
=11。你知道吗可以表示为加权和:
8*a+4*b+2*c+1*d
按定义插入a,b,c,d,你会得到11,但另一种看加权和的方法是:
或者
这里,2的指数是递减的,乘以二进制数。你知道吗
换句话说:
(2**3)*1 + (2**2)*0 + (2**1)*1 + (2**0)*1 == 11
首先反转字符串,然后指数从零开始向上计数可能更容易:
(2**0)*1 + (2**1)*1 + (2**2)*0 + (2**3)*1 == 11
在不透露太多信息的情况下,假设变量
binstr
中包含二进制字符串,我将查看以下输出:或者
有一种方法可能最终看起来像:
但这不是唯一的办法。还有其他方法,包括使用
reduce
(或类似的方法)。你知道吗当然,总有
int(binstr, 2)
但我猜这也是不允许的。你知道吗^{} 构造函数接受可选的基。您可以将
base10
重写为另一种转换方式通常是用
bin
完成的。另一种方法是逐个检查数字的位。您的base2
实现很接近,但不应该在循环中打印。你知道吗比如:
另一种方法是使用} 方法和一个简单但可旋转的方法来按正确的顺序创建数字:
int
的^{monstrosity
str(int(bool(num & (1 << n))))
将2的幂的位标志转换为布尔值,然后使用布尔值的整数表示生成0
或1
的字符串。这相当于做'1' if num & (1 << n) else '0'
。你知道吗相关问题 更多 >
编程相关推荐