代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include
#include
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef int SElemType;
int stacksize;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
SqStack OPND;
SqStack OPTR;
void InitStack(SqStack &OPND)
{
OPND.base=(SElemType*)malloc(MAXSIZE* sizeof(SElemType));
if(!OPND.base) exit(0);
OPND.top=OPND.base;
OPND.stacksize=MAXSIZE;
}
void InitStack2(SqStack &OPTR)
{
OPTR.base=(SElemType*)malloc(MAXSIZE* sizeof(SElemType));
if(!OPTR.base) exit(0);
OPTR.top=OPTR.base;
OPTR.stacksize=MAXSIZE;
}
int In(char ch) // 判断输入字符是否为运算符
{
if(ch==’+’) return OK;
if(ch==’-’) return OK;
if(ch==’*’) return OK;
if(ch==’/’) return OK;
if(ch==’(’) return OK;
if(ch==’)’) return OK;
if(ch==’#’) return OVERFLOW;
return ERROR;
}
char Precede(char a,char b) // 比较符号 a与符号 b的优先级.如 a 优于 b,则返回 ’ > ‘,否则返回 ’ < ’ 或 ’ = ’
{
if(b==’+’)
{
if(a==’(’||a==’#’) return ‘<’;
return ‘>’;
}
if(b==’-’)
{
if(a==’(’||a==’#’) return ‘<’;
return ‘>’;
}
if(b==’’)
{
if(a==’’||a==’/’||a==’)’) return ‘>’;
return ‘<’;
}
if(b==’/’)
{
if(a==’*’||a==’/’||a==’)’) return ‘>’;
return ‘<’;
}
if(b==’(’) return ‘<’;
if(b==’)’)
{
if(a==’(’) return ‘=’;
return ‘>’;
}
if(b==’#’)
{
if(a==’#’) return ‘=’;
return ‘>’;
}
}
double Operate(double a,char theta,double b) // 把 a、b进行二元运算
{
if(theta==’+’) return a+b;
if(theta==’-’) return a-b;
if(theta==’’) return ab;
if(theta==’/’) return a/b;
}
void push(SqStack &s,SElemType e)
{
if(s.top-s.base==s.stacksize)
printf(“栈满”);
*s.top++=e;
}
void pop(SqStack &s)
{
int e;
if(s.top==s.base)
printf(“栈空”);
e=*–s.top;
}
double EvaluateExpression() // 计算过程
{
char str[10010];
SqStack OPND;
SqStack OPTR;
scanf("%s",str);
push(OPTR,’#’);
double a,b,shu=0;
int flag=0;
char theta;
for(int i=0;str[i];i++)
{
if(In(str[i])==0)
{
shu=shu*10+str[i]-‘0’;
flag=1;
}
else
{
if(flag)
{
push(OPND,shu);
shu=0;
flag=0;
}
switch (Precede(OPTR.top(),str[i]))
{
case '<':
push(OPTR,str[i]);
break;
case '>':
theta=OPTR.top();pop(OPND);
b=OPND.top(); pop(OPND);
a=OPND.top(); pop(OPND);
push(OPND,Operate(a,theta,b));
i--; // 这里是因为判断的该符号 str[i] 还没有入栈,故需要回去判断一下
break;
case '=':
pop(OPTR);
break;
}
}
}
return OPND.top();
}
int main()
{
printf("\n请您在输入表达式的结尾加一个符号 ‘#’,以判断您的输入完成\n\n");
printf("\n计算结果为:%.2lf\n",EvaluateExpression());
return 0;
}
‘遇到的问题:
C:\Users\ASUS\Desktop\YOUXIAN.CPP(139) : error C2064: term does not evaluate to a function
C:\Users\ASUS\Desktop\YOUXIAN.CPP(145) : error C2064: term does not evaluate to a function
C:\Users\ASUS\Desktop\YOUXIAN.CPP(146) : error C2064: term does not evaluate to a function
C:\Users\ASUS\Desktop\YOUXIAN.CPP(147) : error C2064: term does not evaluate to a function
C:\Users\ASUS\Desktop\YOUXIAN.CPP(157) : error C2064: term does not evaluate to a function
执行 cl.exe 时出错.
YOUXIAN.OBJ - 1 error(s), 0 warning(s)
’