/*----------------------------------------------------------------------------
第八题:输入两个正整数X,Y,将X,Y化为二进制数,然后将这两个二进制数作二进
制加法运算,再将结果化为十进制数输出。
----------------------------------------------------------------------------*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define N 8
void main()
{
int num1, num2, result = 0;
int NUM1[N] = {0}, NUM2[N] = {0}, RESULT[N + 1] = {0};
int i, temp, addition = 0;
printf( "Please input two active integers(0 ~ %d):", (int)pow(2,N) - 1 );
scanf( "%d%d", &num1, &num2 );
for( i = N - 1; num1 != 0; i -- ) /*把第一个整数转换为二进制数*/
{
NUM1[i] = num1 % 2;
num1 /= 2;
}
for( ; i >= 0; i -- )
NUM1[i] = 0;
printf( "No.1 is:\t" ); /*输出第一个数的二进制形式*/
for( i = 0; i < N; i ++ )
printf( "%d ", NUM1[i] );
printf( "\n" );
for( i = N - 1; num2 != 0; i -- ) /*把第二个整数转换为二进制数*/
{
NUM2[i] = num2 % 2;
num2 /= 2;
}
for( ; i >= 0; i -- )
NUM2[i] = 0;
printf( "No.2 is:\t" ); /*输出第二个数的二进制形式*/
for( i = 0; i < N; i ++ )
printf( "%d ", NUM2[i] );
printf( "\n" );
for( i = N - 1; i >= 0; i -- ) /*在二进制的形势下求两数之和*/
{
temp = NUM1[i] + NUM2[i] + addition;
if( temp == 3 )
{
RESULT[i + 1] = 1;
addition = 1;
}
else if( temp == 2 )
{
RESULT[i + 1] = 0;
addition = 1;
}
else if( temp == 1 )
{
RESULT[i + 1] = 1;
addition = 0;
}
else
{
RESULT[i + 1] = 0;
addition = 0;
}
}
RESULT[0] += addition;
printf( "The sum is: " ); /*输出和的二进制形式*/
for( i = 0; i <=N; i ++ )
printf( "%d ", RESULT[i] );
printf( "\n" );
for( i = 0; i <= N; i ++ ) /*求出和的十进制形式*/
result += RESULT[N - i] * ( (int)pow(2,i) );
printf( "The result is:%d\n", result );
getch();
}