【发布时间】:2026-01-30 03:35:02
【问题描述】:
Python 程序:一个将二进制数转换为十进制数、将十进制数转换为二进制数的工具,以及一个用于加减数字的简单纯文本菜单。
对于创建者,您能否调整代码,使其看起来像您在编辑器中的代码?我看不懂。
import sys
二进制转十进制
def bintodec(binnum):
l = len(binnum)
s = binnum
dec = 0
for i in range(0,l):
b = s[l-i-1]
dec = dec + int(b)*(2**i)
return dec
十进制转二进制
def dectobin(decnum):
if decnum==0:
return "00000000"
bin=""
while decnum>0:
bin = str(decnum%2) + bin
decnum = decnum/2
if len(bin)%8 != 0:
n = 8*(len(bin)/8 + 1) - len(bin)
bin = "0" + bin
return bin
def show_menu():
print ("What do you want to do?")
print ("1. Enter the first number")
print ("2. Enter the second number")
print ("3. Add the two numbers together")
print ("4. Subtract the second number from the first")
print ("5. Exit the program\n")
show_menu()
inp = input()
n1 = ""
n2 = ""
while inp !=5:
if inp=="1":
n1 = str(input("Enter the first number\n"))
print ("The first number chosen is: " + str(n1) + "\n")
show_menu()
if inp=="2":
n2= str(input("Enter the second number\n"))
print ("The first number chosen is: " + str(n1))
print ("The second number chosen is: " + str(n2) +"\n")
show_menu()
if inp=="3":
print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
exit()
if inp=="4":
if bintodec(n2)<bintodec(n1):
print ("For this selection second number should be greater than or equal to first")
else:
print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
exit()
inp = input()
【问题讨论】:
-
抱歉,我在这里编辑代码时遇到了问题,我的问题是,当我运行代码并输入我的数字(例如 1 + 1)时,它会给我一大串数字跨度>
-
删除每行开头的所有 >。然后选择代码并按 ctrl-k。
-
好的,所以你有一些代码要做某事,有什么问题? (即:您遇到的代码有什么问题?)
-
当我运行代码并输入我的第一个和第二个数字并将它们加在一起时,它会给我一个巨大的数字串作为我的答案,而我所做的只是尝试将 1 + 1 加在一起
-
这里有一个 repl 的链接。以防万一这里的编辑不正确repl.it/repls/EvergreenPlainAmericanlobster
标签: python