题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=128
简单说下思路:从字符串最右端开始扫描,遇到数字则入栈,遇到运算符则弹出两个元素计算后再入栈,知道最后栈中最后一个元素就是最后表达式的值。
字符串的处理比较繁琐。充分利用库函数 。
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <stack>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
stack<double> s;
string ex;
while(getline(cin,ex))
{
char tmp;
while(!s.empty())s.pop();
for(int i=ex.size()-1;i>0;i--)
{
tmp=ex[i];
if(tmp==' ')continue;
if(ex[i-1]==' '){
tmp-='0';
if(tmp>0&&tmp<10)
s.push(double(tmp));
else {
tmp+='0';
double a=s.top();
s.pop();
double b=s.top();
s.pop();
double re;
switch(tmp){
case '+':re=a+b;s.push(re);break;
case '-':re=a-b;s.push(re);break;
case '*':re=a*b;s.push(re);break;
case '/':re=a/b;s.push(re);break;
}
}
}
else {
string dot("");
int cnt=0;
dot+=tmp;
int j=i-1;
while(j>=0&&ex[j]!=' '){
dot+=ex[j];
j--;
}
string dot1(dot.size(),' ');
for(int i=dot.size()-1,j=0;i>=0;i--,j++)dot1[j]=dot[i];
char pt[20];
strcpy(pt,dot1.c_str());
double re=atof(pt);
s.push(re);
i=j;
}
}
tmp=ex[0];
double a=s.top();
s.pop();
double b=s.top();
s.pop();
switch(tmp){
case '+':printf("%.2lf\n",a+b);break;
case '-':printf("%.2lf\n",a-b);break;
case '*':printf("%.2lf\n",a*b);break;
case '/':printf("%.2lf\n",a/b);break;
}
}
return 0;
}