大数相加算法的C代码
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define max(a,b) (a)>(b)?(a):(b)
int big_add(char*,char*,char*);
int big_sub(char*,char*,char*);
int big_compare(char*,char*,int*);
int is_number_string(char*);
int main()
{
char num1[80],num2[80],num3[100];
puts("First number:");
gets(num1);
puts("Second number:");
gets(num2);
if(big_add(num1,num2,num3))
{
puts("Sum:");
puts(num3);
big_sub(num1,num2,num3);
puts("Difference::");
puts(num3);
}
else
puts("Input error!");
return 0 ;
}
int big_add(char *num1,char *num2, char *sum)
{
if(is_number_string(num1)&&is_number_string(num2))
{
int len1=strlen(num1),len2=strlen(num2),c=0;
int len=max(len1,len2)+1;
char *res=(char*)malloc((len+1)*sizeof(char));
memset(res,0x30,len*sizeof(char));
res[len]=0;
for(;len>0;len1--,len2--)
{
len--;
len1>0&&(res[len]+=num1[len1-1]-0x30);
len2>0&&(res[len]+=num2[len2-1]-0x30);
res[len]+=c;
if(res[len]>0x39)
{
res[len]-=0xa;
c=1;
}
else
c=0;
}
res[len]+=c;
while(!(*res-0x30))
res++;
strcpy(sum,res);
return(1);
}
return(0);
}
int big_sub(char *num1,char *num2,char *diff)
{
if(is_number_string(num1)&&is_number_string(num2))
{
int com;
big_compare(num1,num2,&com);
if(com>0)
{
int len1=strlen(num1),len2=strlen(num2),c=0;
int len=max(len1,len2)+1;
char *res=(char*)malloc((len+1)*sizeof(char));
memset(res,0x30,len*sizeof(char));
res[len]=0;
for(;len>0;len1--,len2--)
{
len--;
len1>0&&(res[len]+=num1[len1-1]-0x30);
len2>0&&(res[len]-=num2[len2-1]-0x30);
res[len]-=c;
if(res[len]<0x30)
{
res[len]+=0xa;
c=1;
}
else
c=0;
}
res[len]+=c;
while(!(*res-0x30))
res++;
strcpy(diff,res);
}
else
{
*diff='-';
big_sub(num2,num1,diff+1);
}
return(1);
}
else
return(0);
}
int big_compare(char *num1,char *num2,int *result)
{
if(is_number_string(num1)&&is_number_string(num2))
{
int len1=strlen(num1),len2=strlen(num2);
if(len1==len2)
{
while(*num1++==*num2++);
*result=*num1-*num2;
}
else
*result=len1-len2;
return(1);
}
else
return(0);
}
int is_number_string(char *str)
{
for(;*str;str++)
if(*str<'0'||*str>'9')
return(0);
return(1);
}
有梦想就不会觉得苦.
Do you know what is the glittering life?