重点:只能在二进制中检查是否溢出,不能直接通过判断结果是否超过二进制位数所能表达的最大值来判断
def mult(a,b,N=12):#定义一个二进制转换十进制并判断是否溢出函数,位数默认为12
num=int(a,2)*int(b,2)#转换为十进制整数
if -2**(N-1)<=num<=2**(N-1)-1:#判断是否在数据范围内
print(num)
else:
print('溢出错误')
#x,y=map(int,input().split())
for x,y in [(-12,100),(-30,-10),(4,-512),(4,512),(40,80)]:
x1=bin(x)#转十进制数为二进制
y1=bin(y)#同上
mult(x1,y1)#调用函数输出结果
你题目的解答代码如下:
def DtoB(num,N):
L=[]
while num>0:
i = num % 2
L = [i]+L
num = num//2
while(len(L)<N):L=[0] + L
#print(L)
return L
def complement(L,N):
for i in range(N):
if L[i]==0:L[i]=1
else : L[i]=0
L[len(L)-1]+=1
for i in range(len(L)-1,0,-1):
if L[i]==2:
L[i]=0
L[i-1]+=1
#print(L)
if L[0]==2:L[0]=1
#print(L)
return L
def judge(L,N):
if L[0]=="-":
a=L[1:]
a = int(a)
if a > int(pow(2,N-1)+0.5):print("数据溢出")
else:
L = DtoB(a,N)
L = complement(L,N)
else:
a=int(L)
if a > int(pow(2,N-1)-0.5):print("数据溢出")
else: L = DtoB(a,N)
#print(L)
return L
def comp(L):
for i in range(len(L)):
if L[i]==0:L[i]=1
else : L[i]=0
L[len(L)-1]+=1
for i in range(len(L)-1,0,-1):
if L[i]==2:
L[i]=0
L[i-1]+=1
#print(L)
if L[0]==2:L[0]=0
return L
def BtoD(L):
if len(L)==1:return L
else:
L1 = L[:len(L)//2]
L2 = L[len(L)//2:]
for i in range(len(L1)):
L1[i] *= int(pow(2,len(L2)))
return(BtoD(L1)+BtoD(L2))
def multive(L1,L2):
L=[]
while len(L1)<len(L2):
L1=[0]+L1
while len(L1)>len(L2):
L2=[0]+L2
for i in range(len(L1)):
L += [0]
for i in range(len(L1)):
temp = []
for j in range(len(L1)-1,i-1,-1):
temp = [L2[j]*L1[len(L1)-i-1]]+temp
#print(temp,"temp")
for j in range(len(L2)-i):
L[j]+=temp[j]
#print(L,"L")
for i in range(len(L)-1,0,-1):
while L[i]>2:
L[i]-=2
L[i-1]+=1
if L[0] > 0:
print("数据溢出")
else:
Q = 0
L = BtoD(L)
for i in range(len(L)):
Q+=L[i]
print(Q)
def mult(L1,L2):
if L2[0]==0 and L1[0]==0:
multive(L1,L2)
elif L1[0]==1 and L2[0]==0:
L1 = comp(L1)
print("-",end="")
multive(L1,L2)
elif L2[0]==1 and L1[0]==0:
L2 = comp(L2)
print("-",end="")
multive(L1,L2)
else:
L1 = comp(L1)
L2 = comp(L2)
multive(L1,L2)
#N = int(input())
N=int(input("请输入一个正整数表示二进制位数"))
a=input("请输入一个整数")
b=input("请输入一个整数")
L1=judge(a,N)
L2=judge(b,N)
mult(L1,L2)
如有帮助,望采纳!谢谢!