我的位加法器的总和仅在某些时间起作用

时间:2019-05-17 17:51:26

标签: python python-3.x

我的逻辑似乎有问题,因为它并不总是提供正确的输出。例如,当我输入2和2时,我得到[0,0,0,0,0,1,0,1],而我应该得到[0,0,0,0,0,1,0,0]

我认为当我的代码接受2个输入时,我的代码中存在逻辑错误,但我看不到它的来源。

8位二进制加法器

  

下面的代码

#if you have questions about the code just ask



array


# arrays and funtions
Array1 = []
Array2 = []
#Input A and Validation
def vaildNumberA():
    Array1 = []
    a = int(input("Enter your A value:"))
    if (a < 0):
            print("Please Enter A Valid Number For Input A")
    elif (a > 255):
        print("Please Enter A Valid Number For Input A")
    else:
         Array1 = [int(x) for x in list('{0:08b}'.format(a))]

    #Return the array 
    return Array1

#Input B and Validation
def vaildNumberB():

    Array2 = [] 
    b = int(input("Enter your B value:"))
    if (b < 0):
        print("Please Enter A Valid Number For Input B")
    elif (b > 255):
        print("Please Enter A Valid Number For Input B")
    else:
        Array2 = [int(x) for x in list('{0:08b}'.format(b))]

    #Return the array
    return Array2

# AND Gate
def AND (a,b):
    if (a == 1 and b == 1):
        return 1
    else:
        return 0
#OR Gate
def OR(a,b):
    if (a == 1 or b == 1):
       return 1
    else:
        return 0

#XOR Gate   
def XOR (a,b):
    if (a == b):
        return 0
    else: 
        return 1

#carry formula
def carryformula(a,b,c,d):
    return OR(AND(a,b), AND(c,d))

# this is where the calculation should be done
  

loop1

#formula for sum
def calculateSum(Array1,Array2): 
    carry = ""
    sumof = []
    for index in range(len(Array1)):
        list2 = Array2[index]
        sec_xor_form = XOR(Array1[index],Array2[index])
        sumof.append(XOR(sec_xor_form,carry))
        carry = carryformula(Array1[index],Array2[index],sec_xor_form,carry)  
    return list(reversed(sumof))
  

循环

while True:

    #Call the function from within the while True loop 
    Array1 = vaildNumberA()
    Array2 = vaildNumberB()
    total = calculateSum(list(reversed(Array1)),list(reversed(Array2)))
    print(total)
    quit = input("if want to quit type q: ")
  

退出

    if quit == 'q':
        break

1 个答案:

答案 0 :(得分:1)

carry变量应初始化为0而不是空字符串"",以便您的XOR函数可以将a == b评估为{{1 }},并在第一位为True时正确返回0

更改:

0

收件人:

carry = ""