用栈实现大整数加法时,当输入3时,不知问题出在哪?求高手指教!!!
算法的设计思想:1)从左到右按位读入加数1,并存入栈1; 2)从左到右按位读入加数2,并存入栈2;
3)若栈1非空,则栈1出栈赋值给j1, 否则0赋值给j1,若栈2非空,则栈2出栈赋值给j2,否则0赋值给j2,若栈1和栈2均为空栈,则输出栈3.
4)j1加j2加进位(初值为0)的和的个位入栈3,十位赋值给进位,转3.
//顺序栈的实现
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int SElemType;
#define MAXSIZE 100
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//算法3.5 顺序栈的初始化
Status InitStack(SqStack &S)
{
// 构造一个空栈 S
S.base=new SElemType[MAXSIZE]; //为顺序栈分配一个最大容量为MAXSIZE的数组空间
if(!S.base) exit(OVERFLOW); //存储分配失败
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
//算法3.6 顺序栈的入栈
Status Push(SqStack &S, SElemType e)
{//在栈顶插入元素e
if(S.top-S.base==S.stacksize) return ERROR; //栈满
*S.top++=e; //元素e压入栈顶,栈顶指针加1
return OK;
}
//算法3.7 顺序栈的出栈
Status Pop(SqStack &S,SElemType &e)
{// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}
//算法3.4取栈顶元素
SElemType GetTop(SqStack S)
{
if(S.base==S.top) exit(1);
return* (S.top-1);
}
int main()
{
SqStack s1,s2,s3;
SElemType e1,e2;
char c1[100],c2[100];
int a1[100],a2[100],i,j,j1,j2,j3,k,n1=0;
cout<<" 大整数加法计算器\n";
cout<<"* * * * * * * * * * * * * * * * * * * * * *"<<endl;
cout<<"* 1----输入加数1 *"<<endl;
cout<<"* 2----输入加数2 *"<<endl;
cout<<"* 3----输出和 *"<<endl;
cout<<"* 4----输出差 *"<<endl;
cout<<"* 5----退出 *"<<endl;
cout<<"* * * * * * * * * * * * * * * * * * * * * *"<<endl;
int choose=-1;
while(choose)
{
cout<<" 请选择菜单号(0-4):";
cin>>choose;
switch(choose)
{
case 1:
if(InitStack(s1)==OK)
{
cout<<" 请输入加数1:";
cin>>c1;
for(j=0,i=0;i<strlen(c1);i++,j++)
a1[j]=c1[i]-'0';
for(i=0;i<strlen(c1);i++)
Push(s1,a1[i]);
/*
while(s1.base!=s1.top)
{
cout<<*(s1.top-1);
s1.top--;
}*/
}
break;
case 2:
if(InitStack(s2)==OK)
{
cout<<" 请输入加数2:";
cin>>c2;
for(j=0,i=0;i<strlen(c2);i++,j++)
a2[j]=c2[i]-'0';
for(i=0;i<strlen(c2);i++)
Push(s2,a2[i]);
/*
while(s2.base!=s2.top)
{
cout<<*(s2.top-1);
s2.top--;
}*/
}
break;
case 3:
while((s1.top!=s1.base)||(s2.top!=s2.base))
{
if(s1.top==s1.base)
j1=0;
else
if(Pop(s1,e1)==OK)
j1=e1;
if(s2.top==s2.base)
j2=0;
else
if(Pop(s2,e2)==OK)
j2=e2;
j3=j1+j2+n1;
if(j3>=10)
{
j3=j3-10;
if(Push(s3,j3)==OK)
n1=1;
}
else
{
if(Push(s3,j3)==OK)
n1=0;
}
}
cout<<"加数1和加数2的和为:";
while(s3.base!=s3.top)
{
s3.top--;
cout<<*(s3.top);
}
break;
case 4:
}
}
return 0;
}