4位二进制加法 c语言程序如何编写 急用
发布网友
发布时间:2022-09-19 13:15
我来回答
共2个回答
热心网友
时间:2023-10-28 02:20
//...
//自己编译下试试。
//专门为你写的啊,如果可用一定要给分哦。
#include <stdio.h>
#include <stdlib.h>
#define ERR printf
/*
char *myItoa (int n,const char * ch)
{
¡¡sprintf(ch,"%d",n);
¡¡return ch;
}
*/
/*
int binA2Dec(char * ch,int len)
{
int sum,i;
sum = 0;
for(i=len-1;i>=0;i--)
{
sum = sum*2 + (ch[i] - '0');
}
return sum;
}
*/
#define MAX_BIT 4 //可以定义任意位的加减。
int M_num(int base,int b)
{
int tmp;
int multi = 1;
for(tmp=b;tmp;tmp--)
multi = multi * base;
return multi;
}
typedef enum
{
false,
true
}bool;
bool checkBuf(char * ch)
{
int i,j;
if(ch[MAX_BIT] != 0)
{
i = MAX_BIT;
ERR("\nOnly %d bits need!!\n",i);
return false;
}
for(i=0;i<MAX_BIT;i++)
{
if((ch[i] != '0') && (ch[i] != '1') && (ch[i] != 0) )
{
ERR("\nInput binary data,you must reInput!\n");
return false;
}
if(ch[i] == 0)
{
for(j=i-1;j>=0;j--)
{
ch[j+1] = ch[j];
}
ch[0] = '0';
}
}
return true;
}
int bin2Dec(int num)
{
int sum,fig,tmp,numNext;
// Initialization.
numNext = num;
sum = 0;
tmp = 1;
for(;;)
{
fig = numNext%10; // Get lowest number
sum = sum + fig*tmp;
tmp = tmp * 2;
numNext = numNext/10;
if(!numNext)
return sum;
}
}
int dec2bin(int num)
{
int sum,fig,tmp,numNext;
//Initialization
numNext = num;
sum = 0;
tmp = 1;
for(;;)
{
fig = numNext%2; //get current parity digit.
sum = sum + fig*tmp; //sum of demical number add parity.
tmp = tmp*10;
numNext = numNext/2;
if(!numNext)
return sum;
}
}
int main(int argc, char *argv[])
{
char Num1[MAX_BIT+1],Num2[MAX_BIT+1],sum[MAX_BIT+1];
int Number1,Number2,sumNum;
int i;
//Initialize the arrry.
for(i =0;i<(MAX_BIT+1);i++)
{
Num1[i]= Num2[i] = 0;
}
//Process to get input number
//And check the validity of input
printf("\nPlease input number1:\n");
scanf("%s",Num1);
if(!checkBuf(Num1))
{
system("PAUSE");
return 0;
}
printf("\nPlease input number2:\n");
scanf("%s",Num2);
if(!checkBuf(Num2))
{
system("PAUSE");
return 0;
}
// Get number from array.
Number1 = atoi(Num1);
Number2 = atoi(Num2);
// Convert binary data to demical data
Number1 = bin2Dec(Number1);
Number2 = bin2Dec(Number2);
// Sum of two number.
sumNum = Number1 + Number2;
// Convert from demical data to binary data.
sumNum = dec2bin(sumNum);
// Get char array
itoa(sumNum,sum,10);
// Output
if(sumNum >= M_num(10,MAX_BIT) )
{
sumNum=MAX_BIT;
printf("\nThe sum overflow %d bit ..",sumNum);
}
printf("\nthe sum is|%s|\n\n",sum);
system("PAUSE");
return 0;
}
热心网友
时间:2023-10-28 02:20
char a,b,x;
char c;//进位标志
x = (a+b);
c = (x &0x10)>>4;
x = x & 0x0f;