8.
/* 输入两个正整数num_x,num_y,将num_x,num_y化为二进制数,然后将这两个二进制数作二进
制加法运算,再将结果化为十进制数输出。
*/
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
void convert(int ,int[],int);
void array_add(int[],int[],int[],int);
int convert2(int[],int);
int main()
{
int num_x,num_y,sign=1;
const int max=20;
int array_x[max]={0},array_y[max]={0},array_sum[max]={0};//,array_x[32]={0}
cout<<"input the num_x & num_y:\n\r";//input the num_x and num_y
cin>>num_x
>>num_y; //input the number
convert(num_x,array_x,max);//call the function
cout<<"the <"<<num_x<<"> convert into "<<"2"<<" is : ";//print the num_x convert into 2
for(int i=max-1;i>=0;i--)
{
if(!(array_x[i]==0&&sign==1))
{
cout<<array_x[i];
sign=0;
}
}
cout<<endl;
convert(num_y,array_y,max);//call the function
sign=1;
cout<<"the <"<<num_y<<"> convert into "<<"2"<<" is : ";//print the num_x convert into 2
for(int j=max-1;j>=0;j--)
{
if(!(array_y[j]==0&&sign==1))
{
cout<<array_y[j];
sign=0;
}
}
cout<<endl;
sign=1;
array_add(array_x,array_y,array_sum,max);
cout<<"the sum is: ";//print the num_x convert into 2
for(int p=max-1;p>=0;p--)
{
if(!(array_sum[p]==0&&sign==1))
{
cout<<array_sum[p];
sign=0;
}
}
cout<<endl;
cout<<"the sum in the way of 10 is:"<<convert2(array_sum,max)<<endl;
return 0;
}
void convert(int num_x,int array_x[],int size)//change into 2
{
int Remainder1=num_x,i=0;
while(Remainder1!=0)
{
array_x[i++]=Remainder1%2;
Remainder1/=2;
}
}
void array_add(int arr1[],int arr2[],int arr3[],int max)//the sum function
{
int i,j;
for(i=0,j=0;i<max;)
{
arr3[i]=arr1[i]+arr2[i]+arr3[i];
if(arr3[i]==2)
{
arr3[i]=0;
i++;
arr3[i]=1;
}else if(arr3[i]==3)
{
arr3[i]=1;
i++;
arr3[i]=1;
}
else i++;
}
}
int convert2(int arr[],int max)
{
int data=0,i;
for(i=0;i<max;i++)
{
data+=arr[i]*pow(2,i);
}
return data;
}