有点问题,因为你没有给n赋初值,所以n的值不确定,也就是说可能为1,那该if语句就失效了。
另外,其实根本就没必要事先比较s1和s2的长度,模仿递增向量的合并方法,先计算长度相同的部分,之后计算剩余部分。
我用c++的string字符串写了一个,你参考下。
#include<iostream>
#include<string>
using
namespace
std
void
Reverse(string
&
str)
void
AddInt(string
&
c,
string
a,
string
b)
int
main()
{
string
a,
b,
c
cin
>>
a
>>
b
AddInt(c,
a,
b)
cout
<<
a
<<
"
+
"
cout
<<
b
<<
"
=
"
<<
endl
cout
<<
c
<<
endl
system("pause")
return
0
}
void
Reverse(string
&
str)
{
int
left,
right
left
=
0
right
=
str.size()-1
while
(left
<
right)
{
char
ch
=
str[left]
str[left]
=
str[right]
str[right]
=
ch
left++
right--
}
}
void
AddInt(string
&
c,
string
a,
string
b)//模仿递增向量的合并方法
{
c.resize(0)
Reverse(a)
Reverse(b)
//逆序计算a+b,则从低位开始计算
int
i,
carry
i
=
carry
=
0
while
(i
<
a.size()
&&
i
<
b.size())
{
c
+=
(a[i]-'0'
+
b[i]-'0'
+
carry)
%
10
+
'0'
carry
=
(a[i]-'0'
+
b[i]-'0'
+
carry)
/
10
i++
}
while
(i
<
a.size())
{
c
+=
(a[i]-'0'
+
carry)
%
10
+
'0'
carry
=
(a[i]-'0'
+
carry)
/
10
i++
}
while
(i
<
b.size())
{
c
+=
(b[i]-'0'
+
carry)
%
10
+
'0'
carry
=
(b[i]-'0'
+
carry)
/
10
i++
}
while
(carry
>
0)//计算进位部分
{
c
+=
carry
%
10
+
'0'
carry
/=
10
}
i
=
c.size()
-
1
while
(c[i]
==
'0')//消除多余的高位0
{
i--
}
c
=
c.substr(0,
i+1)
Reverse(c)
}
不是我写的,,帮你找到的。。#include<stdio.h>
#include <conio.h>
#include <string.h>
#include "stdlib.h"
void main()
{
int n=0,i=0,j=0,k=0,b=0
char a[3][500]={0}
int n1=0,n2=0
char s[500]={0}
int n3=0
int c=0,c1=0
int temp=0
char op
char str[1001]={0}
char *result
scanf("%d",&n)
result=(char *)malloc(501*n)//根据输入的n申请内存空间
*result='\0'
/*每次循环都要初始化*/
for(i<ni++)
{
//gets(str)
for(j=0j<500j++)
{
a[0][j]='\0'a[1][j]='\0'a[2][j]='\0'
s[j]='\0'
str[j]='\0'
str[1000-j]='\0'
}
c=0c1=0
k=0
n1=0n2=0n3=0
/*分离输入的字符串*/
scanf("%s",&str)
for( j=0str[j]j++ )
{
if( str[j]!='+' && str[j]!='-')
a[k][j-n1]=str[j]
else
{
op=str[j]
k=1
n1=strlen(a[0])+1
}
}//for j
n1-=2
n2=strlen(a[1])-1
n3=n1>n2?n1:n2
/*计算加法*/
if(op=='+')
{
for(n1>=0&&n2>=0n1--,n2--,n3--)
{
temp=a[0][n1]+a[1][n2]-96
temp+=c
if(temp>=10)
{
s[n3]=temp%10+48
c=1
}
else
{
s[n3]=temp+48
c=0
}
}//for
while(n1>=0)
{
temp=a[0][n1]-48
temp+=c
if(temp==10)
{
s[n3]=48
c=1
}
else
{
s[n3]=temp+48
c=0
}
n1--
n3--
}//while n1
while(n2>=0)
{
temp=a[1][n2]-48
temp+=c
if(temp==10)
{
s[n3]=48
c=1
}
else
{
s[n3]=temp+48
c=0
}
n2--
n3--
}//while n2
if(c)
strcat(result,"1")
strcat(result,s)
strcat(result,"\n")
}//if op
/*计算减法*/
else
*如果被减数大于减数,则交换2数,并设置变量
*/
if(strcmp(a[0],a[1])<0)
{
//a[2]=a[0]a[0]=a[1]a[1]=a[2]
for(b=0b<3b++)
{
j=(b+2)%3
for(k=0k<=n2k++)
a[j][k]=a[b][k]
}
n2=n1n1=n3
c1=1//正为0,负为1
}
/*计算减法*/
for(n2>=0n1--,n2--,n3--)
{
temp=a[0][n1]-a[1][n2]
temp-=c
if(temp>=0)
{
s[n3]=temp+48
c=0
}
else
{
s[n3]=temp+58
c=1
}
}//for
while(n1>=0)
{
temp=a[0][n1]-48
temp-=c
if(temp>=0)
{
s[n3]=temp+48
c=0
}
else
{
s[n3]=temp+58
c=1
}
n1--
n3--
}
if(c1)
strcat(result,"-")
/*消除减法结果高位的0*/
j=0
while(s[j]==48)
j++
strcat(result,s+j)
strcat(result,"\n")
}//else op
}//for i
printf("%s",result)
getch()()
}