帮助,设计一个4位加法器。程序应该将2个十进制转换为二进制,然后加上2给出一个总和并作为最终结果携带。 [英] Help,design a 4 bit adder.The program should convert 2 decimal to binary then add the 2 giving a sum and carry as the final result.

查看:61
本文介绍了帮助,设计一个4位加法器。程序应该将2个十进制转换为二进制,然后加上2给出一个总和并作为最终结果携带。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
int main()
{

bool ar[4],arr[4] ;
int i=0,h=0,j,k;
int n,m,carry=0,result[5];
cout<<"Enter the first positive number:"<<"\n";
cin>>n;
while(n>0)
{
    ar[i]=n%2;
    i++;
    n=n/2;

}

cout<<"Binary number is:";
for (j=i-1;j>=0;j--)
{
    cout<<ar[j];
    }
cout<<"\n"<<"Enter the 2nd positive number:"<<"\n";
cin>>m;
while(m>0)
{
    arr[h]=m%2;
    h++;
    m=m/2;

}

cout<<"Binary number is:";
for (k=h-1;k>=0;k--)
{
    cout<<arr[k];
    }

    cout<<"\n";

推荐答案

根据您的描述,您需要在硬件类全加器方面实现多少?如果它只是产生结果,你可以非常简化代码,例如(没有尝试使用编译器 - 从大脑到纸张;-)):

From your description it is not obvious how much you need to implement in terms of hardware-like full adder? If it's just about producing the result, you may very much simplify the code, e.g. (not tried with the compiler - from brain to paper ;-)):
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
    unsigned int a;
    unsigned int b;
    cin >> a >> b;
    if (a < 0x10 && b < 0x10)
    {
        unsigned int r = a + b;
        unsigned int c = r & 0x10 ? 1 : 0;
        r &= 0x0F;
        cout << "carry = " << c << ", 4-bit result = " << r << endl;
    }
}



既然你不清楚是否需要将结果转储为二进制或十进制,我决定尽量减少:十进制;-)。

问候

Andi


Since it was neither clear if you need to dump the result as binary or as decimal, I decided for the least effort: decimal ;-).
Regards
Andi


您提供的代码已经错误: ar arr 未初始化为零。

纠正它的一种方法是:

The code you provided is already buggy: ar and arr are not initialised to zero.
One way to correct it is:
for(i=0; i < 4, i++)
{
    ar[i]=n%2;
    n=n/2;
}



此代码将填写 ar 并同时归零。



你对比特加法器做了什么?

顺便说一句,我们不为你做功课,如果你有问题,我们会帮忙在你完成的工作中。


This code will fill ar and zero it at the same time.

What have you done about the bits adder ?
By the way we don't do your homework for you, we just help if you have a problem in the work you have done.


这篇关于帮助,设计一个4位加法器。程序应该将2个十进制转换为二进制,然后加上2给出一个总和并作为最终结果携带。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆