有关中缀表达式的计算以及中缀表达式与前缀表达式、后缀表达式之间的转换 后续文章会继续给出
这里只讲前缀表达式与后缀表达式计算的实现方法
前缀表达式
计算方法:
将得到的字符串处理为只含有数字和运算符
将处理后的字符串从前到后压如栈S1中
将栈S1中的元素逐个弹出
若弹出元素判断为数字 压入栈S2中
若弹出元素判断为运算符 从栈S2中弹出两个元素 与该运算符进行运算 将运算结果重新压入栈S2中
处理完S1中所有元素后 S2栈顶元素即为计算结果
实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stack>
using namespace std;
char *Sep=" ";
char *p;
char str[1005];
double calculate(double a,double b,char c){// 元素的运算顺序和后缀表达式相反
if(c=='+') return a+b;
if(c=='-') return a-b;
if(c=='*') return a*b;
if(c=='/') return a/b;
}
int main (){
while (gets(str)){
stack<char*> S1;
stack<double> S2;
p=strtok(str,Sep);// 字符串处理 以空格为分隔符将字符串分隔 压入栈中
do{
S1.push(p);
}while ((p=strtok(NULL,Sep)));
while (!S1.empty()){
p=S1.top();
S1.pop();
if (isdigit(p[0]))// 判断是否为数字
S2.push(atof(p));
else{
double a=S2.top();
S2.pop();
double b=S2.top();
S2.pop();
double temp=calculate(a,b,p[0]);
S2.push(temp);// 计算结果重新压入栈
}
}
printf ("%g\n",S2.top());// 格式控制 随便啦 根据题意就好
}
return 0;
}
后缀表达式
计算方法:
将得到的字符串处理为只含有数字和运算符
从前到后判断分隔后的字符
若判断为数字压入栈中
若判断为运算符 从栈中弹出两个元素 与该运算符进行运算 将运算结果重新压入栈中
处理完所有分隔后的字符 栈顶元素即为计算结果
实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stack>
using namespace std;
char *Sep=" ";
char *p;
char str[1005];
double calculate(double a,double b,char c){
if(c=='+') return b+a;
if(c=='-') return b-a;
if(c=='*') return b*a;
if(c=='/') return b/a;
}
int main (){
while (gets(str)){
stack<double> S;
p=strtok(str,Sep);
do{
if (isdigit(p[0]))
S.push(atof(p));
else{
double a=S.top();
S.pop();
double b=S.top();
S.pop();
double temp=calculate(a,b,p[0]);
S.push(temp);
}
}while ((p=strtok(NULL,Sep)));
printf ("%g\n",S.top());
}
return 0;
}
中缀表达式现在写了
中缀表达式的计算 : http://blog.csdn.net/mm__1997/article/details/78115962
附一前缀表达式计算的练习题目:http://acm.nyist.net/JudgeOnline/problem.php?pid=128