#include "stdio.h"
#include "string.h"
void fun1(char *s1,char *s2,char *sum)
{ char ch;
int i,j,t;
for(i=0;i<100;i++)
sum[i]='0';
i=strlen(s1)-1;
j=strlen(s2)-1;
if(i>j) t=i;
else t=j;
sum[t+2]='\0';
for(t++;i>=0&&j>=0;i--,j--)
{ ch=s1[i]+s2[j]-'0'-'0';
if(ch+sum[t]<=57)
sum[t--]=sum[t]+ch;
else
{ sum[t-1]='1';
sum[t]=sum[t]+ch-10;
t-=1;
}
}
if(i>0)
for(;i>=0;i--)
{ if(sum[t]+s1[i]-'0'<='9')
sum[t--]=sum[t]+s1[i]-'0';
else
{ sum[t-1]='1';
sum[t--]=sum[t]+s1[i]-'0'-10;
}
}
else
for(;j>=0;j--)
{ if(sum[t]+s2[j]-'0'<='9')
sum[t--]=sum[t]+s2[j]-'0';
else
{ sum[t-1]='1';
sum[t--]=sum[t]+s2[j]-'0'-10;
}
}
}
void main()
{
char s1[100],s2[100],sum[120]="0";
int i,j;
printf(" input s1:");
gets(s1);
printf(" input s2:");
gets(s2);
if(s1[0]!='-'&&s2[0]!='-')
{ fun1(s1,s2,sum);
printf(" output sum:");
if(sum[0]!='0')
puts(sum);
else puts(sum+1);
}
else if(s1[0]=='-'&&s2[0]=='-')
{ fun1(s1+1,s2+1,sum+1);
sum[0]='-';
printf(" output sum:");
if(sum[1]!='0')
puts(sum);
else
{ sum[1]='-';
puts(sum+1);
}
}
}
这个程序只能完成同号相加
#include "string.h"
void fun1(char *s1,char *s2,char *sum)
{ char ch;
int i,j,t;
for(i=0;i<100;i++)
sum[i]='0';
i=strlen(s1)-1;
j=strlen(s2)-1;
if(i>j) t=i;
else t=j;
sum[t+2]='\0';
for(t++;i>=0&&j>=0;i--,j--)
{ ch=s1[i]+s2[j]-'0'-'0';
if(ch+sum[t]<=57)
sum[t--]=sum[t]+ch;
else
{ sum[t-1]='1';
sum[t]=sum[t]+ch-10;
t-=1;
}
}
if(i>0)
for(;i>=0;i--)
{ if(sum[t]+s1[i]-'0'<='9')
sum[t--]=sum[t]+s1[i]-'0';
else
{ sum[t-1]='1';
sum[t--]=sum[t]+s1[i]-'0'-10;
}
}
else
for(;j>=0;j--)
{ if(sum[t]+s2[j]-'0'<='9')
sum[t--]=sum[t]+s2[j]-'0';
else
{ sum[t-1]='1';
sum[t--]=sum[t]+s2[j]-'0'-10;
}
}
}
void main()
{
char s1[100],s2[100],sum[120]="0";
int i,j;
printf(" input s1:");
gets(s1);
printf(" input s2:");
gets(s2);
if(s1[0]!='-'&&s2[0]!='-')
{ fun1(s1,s2,sum);
printf(" output sum:");
if(sum[0]!='0')
puts(sum);
else puts(sum+1);
}
else if(s1[0]=='-'&&s2[0]=='-')
{ fun1(s1+1,s2+1,sum+1);
sum[0]='-';
printf(" output sum:");
if(sum[1]!='0')
puts(sum);
else
{ sum[1]='-';
puts(sum+1);
}
}
}
这个程序只能完成同号相加