C语言大数相加

#include <stdio.h>
#include <string.h>
#define N 20
 void sum(char ch1[],char ch2[])
 {
char ch3[N];
int num[N],i,j ;
// scanf("%s%s",ch1,ch2);
int m,n,k,t,s;
m = strlen(ch1);
n = strlen(ch2);
k = m<n?n:m;
// printf("m = %d,n=%d,k=%d\n",m,n,k);
s=k;
for(i=0;i<=k;i++) num[i]=0;
for(i=m-1,j=n-1;i>=0&&j>=0;i--,j--)
{
t=(ch1[i]-'0')+(ch2[j]-'0');
num[s--] = t;//字符串相加,结果保存在int数组中
//printf("i=%d,j=%d,t=%d\n",i,j,t);  
}

while(i>=0)
{
num[s--] = ch1[i--]-'0';
}
while(j>=0)
{
num[s--] = ch2[j--]-'0';
}
// printf("i=%d,j=%d,s=%d\n",i,j,s);
for(i=k;i>=1;i--)
{
if(num[i]>9)
{
num[i] -= 10;
num[i-1] += 1; 
}
}
if(num[0]==0)
{
ch3[k] = '\0';
for(i=1;i<=k;i++) ch3[i-1] = (char)(num[i]+'0');//将int数组转化为字符串
}
else
{
ch3[k+1] = '\0';
for(i=0;i<=k;i++) ch3[i] = (char)(num[i]+'0');
}
printf("%s+%s=%s\n",ch1,ch2,ch3);
return ;
 }


 int main()
 {
char ch1[N],ch2[N];
int i=1,n;
scanf("%d",&n);
while(i<=n)
{
scanf("%s%s",ch1,ch2);
printf("Case %d :\n",i);
sum(ch1,ch2);
i++;
}
return 0;
 }

你可能感兴趣的:(c,语言,include)