前缀式计算 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 先说明一下什么是中缀式: 如2+(3+4)5这种我们最常见的式子就是中缀式。 而把中缀式按运算顺序加上括号就是:(2+((3+4)5)) 然后把运算符写到括号前面就是+(2 *( +(3 4) 5) ) 把括号去掉就是:+ 2 * + 3 4 5 最后这个式子就是该表达式的前缀表示。 给你一个前缀表达式,请你计算出该前缀式的值。 比如: + 2 * + 3 4 5的值就是 37 输入 有多组测试数据,每组测试数据占一行,任意两个操作符之间,任意两个操作数之间,操作数与操作符之间都有一个空格。输入的两个操作数可能是小数,数据保证输入的数都是正数,并且都小于10,操作数数目不超过500。 以EOF为输入结束的标志。 输出 对每组数据,输出该前缀表达式的值。输出结果保留两位小数。 样例输入 + 2 * + 3 4 5 + 5.1 / 3 7 样例输出 37.00 5.53
前缀表达式计算要从后往前遍历,遇到操作数压栈,遇到操作符则弹出两个数进行运算后,并将结果压栈(后缀表达式正好相反,从前往后遍历即可)。 这样来看,思路就就比较明确。 这里用了一个规则,带小数点的数长度一定是大于1的,长度等于1的字符要么是操作数,要么是操作符。
#include<cstdio> #include<cstring> #include<stack> using namespace std; stack<double> Oper; double Operate(char ope) { double a,b; a=Oper.top();Oper.pop(); b=Oper.top();Oper.pop(); if(ope=='+') return a+b; else if(ope=='-') return a-b; else if(ope=='*') return a*b; else if(ope=='/') return a/b; } int main(void) { char str[2000]; int slength; while(gets(str)) { slength=strlen(str); double tempnum=0; int i,j,k=0,dot=0; i=j=(slength-1); while(i>=0) { if(str[i]==' ') { tempnum=0; if((j-i)>1) //说明是小数 { for(k=i+1;k<=j;k++) { if(str[k]!='.') tempnum=tempnum*10+str[k]-'0'; else dot=k; } tempnum=tempnum/(10*(j-dot)); // printf("push2: %f \n",tempnum); Oper.push(tempnum); } else { if(str[i+1]>='0' && str[i+1]<='9') { // printf("push1: %d \n",str[i+1]-'0'); Oper.push((double)(str[i+1]-'0')); } else //说明是操作符 Oper.push(Operate(str[i+1])); } j=i-1; } if(i==0) //因为首位没空格,比较特殊,单独处理。规则:它必定是一个操作符 printf("%.2lf\n",Operate(str[i])); i--; } } }另外,可以用stringstream 写出一个超简单的计算方法。代码如下:
#include<iostream> #include<cstring> #include<cstdio> #include<sstream> #include<cstdlib> #include<string> #include<algorithm> using namespace std; stringstream s; string str; double ac() { string str; s>>str; //从流中取出字符串 if(str[0] == '+') return ac() + ac(); if(str[0] == '-') return ac() - ac(); if(str[0] == '*') return ac() * ac(); if(str[0] == '/') return ac() / ac(); return atof(str.c_str()); //返回double类型数据,遇非数字字符停止 } int main() { while(getline(cin, str)) { s.clear(); s<<str; printf("%.2lf\n", ac()); } return 0; }
查看原文:http://www.wyblog.cn/2016/10/30/%e6%95%b0%e6%8d%ae%e7%bb%93%e6%9e%84%e6%a0%88-%e5%89%8d%e7%bc%80%e8%a1%a8%e8%be%be%e5%bc%8f%e8%ae%a1%e7%ae%97/
数据结构栈——前缀表达式计算
最新推荐文章于 2024-01-30 21:58:34 发布