java 4位 二进制,使用加法器电路添加两个4位二进制数

我需要编写一个程序,使用加法器电路添加两个4位二进制数字,为我们提供答案 . 我需要使用int()函数将其从二进制转换为十进制(两个值都需要显示) . 我正在努力创建一个创建正确的二进制和十进制输出的代码 . 我们输入两组四位数字 . 数字应该通过电路,结果应该加在一起 . 现在大门都很好 . 但是,我无法正确地将数字加在一起 . 通过电路的二进制加法是不正确的 . 转换器和输入都是正确的 .

用户需要为x(x1,x2,x3,x4)和y(y1,y2,y3,y4)和ci = 0输入4位二进制数 . 例如:x = 1111 y = 0000

这是我目前的代码:

import string

print('Simple Circuits for Final Project')

x = input('x| enter 4 digits: ')

y = input('y| enter 4 digits: ')

list1 = list(x)

print(list1)

list2 = list(y)

print(list2)

#define all the gates

def xorgate(x,y):

if x == y:

return '0'

else:

return '1'

def andgate (x,y):

if x == '1' and y == '1':

return '1'

else:

return '0'

def orgate (x,y):

if x == '1' or y == '1':

return '1'

else:

return '0'

#define the entire circuit and input the list of inputs for the circuit.

#include the outputs based on the gates defined above.

def circuit(x,y,ci):

a = 3 #starting value for the while loop, get approp position for our list

adder = ['0','0','0','0','0']#adder list only has strings of zero. list to hold binary numbers from the output of the adding circuit

b = 4

while a >= 0:

xorout = xorgate(x[a],y[a])

print("xor:",(xorout))

s = xorgate(ci,xorout)

print("Ci:",ci)

andout = andgate(xorout, ci)

print("and1:",andout)

and2out = andgate(x[a],y[a])

print("and2:",and2out)

co = orgate(andout,and2out)

print('s:',s)

print('co:',co)

print('-----------------')

ci = co

adder[b] = str(s)

a-=1

b-=1

adder[4]=ci

#print(final)

print('The Final Binary Output is:', adder[::-1])

#OUR CONVERTER IS RIGHT, BUT WE CAN'T GET THE BINARY ADDITION ACCURATE

outputfinal = ((int(adder[4]) * 16) + (int(adder[3]) * 8)+(int(adder[2]) * 4)+(int(adder[1]) * 2)+(int(adder[0]) * 1))

print('The Final Decimal Output is:', outputfinal)

hold = '0'

circuit(list1,list2,hold)# 3 value for circuit

这是我们认为错误的部分:

ci = co

adder[b] = str(s)

a-=1

b-=1

adder[4]=ci

#print(final)

print('The Final Binary Output is:', adder[::-1])

这是我当前的输出,这是错误的:

x| enter 4 digits: 1111

y| enter 4 digits: 0000

['1', '1', '1', '1']

['0', '0', '0', '0']

xor: 1

Ci: 0

and1: 0

and2: 0

s: 1

co: 0

-----------------

xor: 1

Ci: 0

and1: 0

and2: 0

s: 1

co: 0

-----------------

xor: 1

Ci: 0

and1: 0

and2: 0

s: 1

co: 0

-----------------

xor: 1

Ci: 0

and1: 0

and2: 0

s: 1

co: 0

-----------------

The Final Binary Output is: ['0', '1', '1', '1', '0']

The Final Decimal Output is: 14

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值