【发布时间】:2015-02-04 05:49:12
【问题描述】:
我正在尝试用 Python 编写一个简单的二进制加法程序(我知道 Python 已经可以做到,我只是在练习基本的计算概念)。我让它工作得很好,唯一奇怪的是,当一个数字比另一个数字长并且从 0 开始时,程序不会返回预期的结果:
#Binary Adding Machine
def add(a,b):
#create empty variables
result=""
state=0
#equalize string lengths
if a>=b:
c=a
b="0"*(len(a)-len(b))+b
else:
c=b
a="0"*(len(b)-len(a))+a
#add strings together into result, in reverse order
for i in range(1,(len(c)+1)):
if state==0:
if a[-i]==b[-i]=="0":
result+="0"
state=0
elif ((a[-i]=="0" and b[-i]=="1") or (a[-i]=="1" and b[-i]=="0")):
result+="1"
state=0
elif a[-i]==b[-i]=="1":
result+="0"
state=1
elif state==1:
if a[-i]==b[-i]=="0":
result+="1"
state=0
elif ((a[-i]=="0" and b[-i]=="1") or (a[-i]=="1" and b[-i]=="0")):
result+="0"
state=1
elif a[-i]==b[-i]=="1":
result+="1"
state=1
#add another "1" if final state is 1
if state==1:
result+="1"
state=0
#reverse string
return result[::-1]
print(add("110101","1111010"))
print(add("1","100000"))
print(add("1","1"))
print(add("100","100"))
print(add("000100100","100"))
print(add("100100100","100"))
如果您运行程序,将打印以下数字:
10101111
100001
10
1000
1000
100101000
倒数第二行应该返回000101000,但它却返回1000。但是,如果数字从 1 开始,它就可以正常工作,正如我们在最后一行中看到的那样。
谁能知道为什么会这样?
非常感谢。
【问题讨论】:
标签: python binary add turing-machines