#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
string str;
stack<char> op;
stack<double> num;
bool In(string s)
{
if (s.length() > 1)
{
return false;
}
else if (s[0] - '0' >= 0 && s[0] - '0' <= 9)
{
return false;
}
else
return true;
}
char ope[7][8]={
{ '=','<','<','<','<','<','<' },
{ '>','>','>','<','<','<','>' },
{ '>','>','>','<','<','<','>' },
{ '>','>','>','>','>','<','>' },
{ '>','>','>','>','>','<','>' },
{ '>','<','<','<','<','<','=' },
{ '>','>','>','>','>','=','>' }
};
int getnum(char c)
{
switch (c)
{
case '#':
return 0;
case '+':
return 1;
case '-':
return 2;
case '*':
return 3;
case '/':
return 4;
case '(':
return 5;
case ')':
return 6;
}
}
char Precede(char c, string s)
{
return ope[getnum(c)][getnum(s[0])];
}
double operate(double d1, char c, double d2)
{
switch (c)
{
case '+':
return d1 + d2;
case '-':
return d2 - d1;
case '*':
return d1*d2;
case '/':
return d2 / d1;
}
}
int main()
{
while (getline(cin,str))
{
if (str == "0")
break;
vector<string> s;
int t = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ' ')
{
string ss = str.substr(t, i - t);
s.push_back(ss);
t = i + 1;
}
else if (i == str.length() - 1)
{
string ss = str.substr(t);
s.push_back(ss);
}
}
s.push_back("#");
stack<double> num;
stack<char> op;
op.push('#');
int i = 0;
while(s[i]!="#" || op.top()!='#')
{
if (!In(s[i]))
{
num.push(atoi(s[i].c_str()));
}
else
{
char c;
double d1, d2;
switch (Precede(op.top(), s[i]))
{
case '<':
op.push(s[i][0]);
break;
case '>':
c = op.top();
op.pop();
d1 = num.top();
num.pop();
d2 = num.top();
num.pop();
num.push(operate(d1, c, d2));
if(s[i][0]!='#')
op.push(s[i][0]);
break;
case '=':
op.pop();
break;
}
}
if(i<s.size()-1)
i++;
}
printf("%.2f\n", num.top());
}
return 0;
}
书上代码