利用栈实现算术表达式的求值,表达式中可以包含加、减、乘、除、乘方、括号运算符,参加运算的操作数可以是实数.Input 输

问题描述:

利用栈实现算术表达式的求值,表达式中可以包含加、减、乘、除、乘方、括号运算符,参加运算的操作数可以是实数.Input 输入一个算术表达式,以‘#’结尾,Output 输出算术表达式的结果(保留两位小数).
1个回答 分类:综合 2014-11-13

问题解答:

我来补答
#define Stack_init_size 100
#define Stack_add 10
#include
using namespace std;
#include
#include
#include
#include
typedef struct{
\x09char *base;
\x09char *top;
\x09int stacksize;
}SqStack1;
typedef struct{
\x09double *base;
\x09double *top;
\x09int stacksize;
}SqStack2;
void InitStack(SqStack1 &S)
{
\x09S.base=(char *)malloc(Stack_init_size*sizeof(char));
\x09if(!S.base)
\x09\x09exit(1);
\x09S.top=S.base;
\x09S.stacksize=Stack_init_size;
\x09return;
}
void InitStack(SqStack2 &S)
{
\x09S.base=(double *)malloc(Stack_init_size*sizeof(double));
\x09if(!S.base)
\x09\x09exit(1);
\x09S.top=S.base;
\x09S.stacksize=Stack_init_size;
\x09return;
}
void Push(SqStack1 &S,char e)
{
\x09if(S.top-S.base>=S.stacksize)
\x09{
\x09\x09S.base=(char *)realloc(S.base,(S.stacksize+Stack_add)*sizeof(char));
\x09\x09if(!S.base)
\x09\x09\x09exit(1);
\x09\x09S.stacksize+=Stack_add;
\x09}
\x09*S.top++=e;
\x09return;
}
void Push(SqStack2 &S,double e)
{
\x09if(S.top-S.base>=S.stacksize)
\x09{
\x09\x09S.base=(double *)realloc(S.base,(S.stacksize+Stack_add)*sizeof(double));
\x09\x09if(!S.base)
\x09\x09\x09exit(1);
\x09\x09S.top=S.base+S.stacksize;
\x09\x09S.stacksize+=Stack_add;
\x09}
\x09*S.top++=e;
\x09return;
}
bool Pop(SqStack1 &S,char &e)
{
\x09if(S.base==S.top)
\x09\x09return false;
\x09e=*(--S.top);
\x09return true;
}
bool Pop(SqStack2 &S,double &e)
{
\x09if(S.base==S.top)
\x09\x09return false;
\x09e=*(--S.top);
\x09return true;
}
char GetTop(SqStack1 &S)
{
\x09if(S.base==S.top)
\x09\x09return 0;
\x09return *(S.top-1);
}
double GetTop(SqStack2 &S)
{
\x09if(S.base==S.top)
\x09\x09return 0;
\x09return *(S.top-1);
}
bool In(char c)
{
\x09if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#'||c=='^')
\x09\x09return true;
\x09return false;
}
double todouble(char s[])
{
double val,power;
int i=0,sign;
sign = (s[i] == '-')?-1 :1;
if(s[i] == '+' || s[i] == '-')
i++;
for(val = 0.0; isdigit(s[i]); i++)
{
val = val * 10 + (s[i] - '0');
}
if(s[i] == '.')
i++;
for(power = 1.0; isdigit(s[i]); i++)
{
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
return sign * val / power;
}
double power(double a,double b)
{
\x09double s=1.0;
\x09for(int i=0;i
 
 
展开全文阅读
剩余:2000