c++ - modifying the addition of two binary numbers in my code -
i trying add together binary numbers in programme im not happy have,my code adds binary numbers
1010 +1111
but want alter when come in binary number 100010001 should add together 1010 +1111 code automatically adds because of 2 arrays , values in array want come in binary number keybord , should above illustration code
int main() { int a[4]; int b[4]; int carry=0; int result[5]; a[0]=1; a[1]=0; a[2]=0; a[3]=1; b[0]=1; b[1]=1; b[2]=1; b[3]=1; for(int i=0; i<4; i++) { if(a[i]+b[i]+carry==3) { result[i]=1; carry=1; } if(a[i]+b[i]+carry==2) { result[i]=0; carry=1; } if(a[i]+b[i]+carry==1) { result[i]=1; carry=0; } if(a[i]+b[i]+carry==0) { result[i]=0; carry=0; } } result[4]=carry; for(int j=4; j>=0; j--) { cout<<result[j]; } cout<<endl; homecoming 0; }
im newbie many if there mistakes please right me , give me best advise in advance
well first thing see not starting @ right-most bit. add-on binary numbers same real base of operations 10 numbers in start @ right , work towards left, whatever bit have left, append origin of sum.
so yours:
9 + 15
1001 + 1111
i = 3 --> [][][][0] -->carry = 1
i = 2 --->[][][0][0] --->carry = 1
i = 1 --->[][0][0][0] --->carry = 1
i = 0 --->[1][0][0][0] --->carry = 1
oh noes ran out of space
so append carry front end of sum:
[1][1][0][0][0] ---> 24
c++
No comments:
Post a Comment