http://acm.hdu.edu.cn/showproblem.php?pid=1237
分析:
中缀表达式求值 题目中没有括号 代码里加了括号
首先知道运算符的优先关系
计算方法
设置两个栈 一个符号栈 一个数字栈
初始化符号栈 将一个 "#" 压入占中
将得到的字符串处理为只含有数字和运算符 末尾加入 "#"
扫描处理后的字符串
如果扫描为运算符 将该运算符与符号栈栈顶运算符比较
如果栈顶运算符优先级低于该运算符 该运算符入栈
如果栈顶运算符优先级等于该运算符 托括号操作 弹出栈顶运算符
如果栈顶运算符优先级高于该运算符 从数字栈中弹出两个数字与栈顶运算符运算 将计算结果重新压入数字栈 并将栈顶运算符弹出 该运算符入栈
如果扫描为数字 将数字压入数字栈
最后 数字栈栈顶元素即为结果
代码写的相当丑 还望指正
AC代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stack>
using namespace std;
char str[1005];
char ans[1005][1005];
char *Sep=" ";
char *p;
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 judge(char p1,char p2){
if (p1=='+'||p1=='-'){
if (p2=='+'||p2=='-'||p2==')'||p2=='#') return 1;
else return -1;
}
else if (p1=='*'||p1=='/'){
if (p2=='(') return -1;
else return 1;
}
else if (p1=='('){
if (p2==')') return 0;
else return -1;
}
else if (p1==')') return 1;
else if (p1=='#'){
if (p2=='#') return 0;
else return -1;
}
}
int main (){
while (gets(str)){
int len=strlen(str);
str[len]=' ';
str[len+1]='#';
stack<char> S1; // 符号栈
stack<double> S2; // 数字栈
S1.push('#');
p=strtok(str,Sep);
int l=0;
memset(ans,0,sizeof(ans));
do{strcpy(ans[l++],p);}while((p=strtok(NULL,Sep)));
if (!strcmp(ans[0],"0")&&l==2) break;
int index=0;
while (ans[index][0]!='#'||S1.top()!='#'){
if (!isdigit(ans[index][0])){// 为运算符
char temp=S1.top();
int tt=judge(temp,ans[index][0]);
if (tt==-1){
S1.push(ans[index][0]);index++;
}
else if (tt==0){
S1.pop();index++;
}
else if (tt==1){
double a=S2.top();
S2.pop();
double b=S2.top();
S2.pop();
S2.push(calculate(b,a,S1.top()));
S1.pop();
}
}
else {// 为数字
S2.push(atof(ans[index]));index++;
}
}
printf ("%.2lf\n",S2.top());
}
return 0;
}
这里是前缀表达式和后缀表达式的求值 http://blog.csdn.net/mm__1997/article/details/72964903