二进制减法-Python [英] Binary Subtraction - Python
问题描述
我想做一个二进制计算器,而减法部分有问题.这是我的代码(我尝试将其修改为我在本网站上找到的总和).
I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) - int(s2[i])
if s <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
该程序在进行某些二进制减法后可以正常工作,但在其他情况下则失败. 有人可以帮我,因为我找不到错误吗?非常感谢.
The program works fine with some binaries subtraction but it fails with others. Can someone please help me because I can't find the mistake? Thanks a lot.
推荐答案
简短答案:对于s1[i] == s2[i]
和carry == 1
,您的代码是错误的.
Short answer: Your code is wrong for the case when s1[i] == s2[i]
and carry == 1
.
更广泛的答案:您应该重组代码,使s==-1
,s==0
和s==1
具有三个独立的大小写,然后在每种情况下分支carry
的值:
Longer answer: You should restructure your code to have three separate cases for s==-1
, s==0
, and s==1
, and then branch on the value of carry
within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
这样,您就每种可能性都有一个单独的障碍,因此没有机会像您初次尝试那样忽略案件.
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
这篇关于二进制减法-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!