輸入
後綴表達式
輸出
計算結果
樣例輸入
3 6 10 2 / - 3 * +
樣例輸出
The result = 6
code如下
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cstdlib>
#include<stack>
using namespace std;
void SplitString(const string& s, vector<string>& v, const string& c)
{
string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while(string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length())
v.push_back(s.substr(pos1));
}
int main()
{
stack<int>s;
string word;
vector<string> a;
getline(cin,word);
SplitString(word,a," ");
for (string::size_type i = 0; i!=a.size();++i)
{
if (a[i] >= "0"&&a[i] <= "9")
{
s.push(atoi(a[i].c_str()));
}
else
{
if (a[i] == " ")continue;
if (a[i] == "-")
{
int b = s.top();
s.pop();
int a = s.top();
s.pop();
int sum = a - b;
s.push(sum);
}
if (a[i] == "+")
{
int b = s.top();
s.pop();
int a = s.top();
s.pop();
int sum = a + b;
s.push(sum);
}
if (a[i] == "/")
{
int b = s.top();
s.pop();
int a = s.top();
s.pop();
int sum = a / b;
s.push(sum);
}
if (a[i] == "*")
{
int b = s.top();
s.pop();
int a = s.top();
s.pop();
int sum = a * b;
s.push(sum);
}
}
}
cout << "The result = "<<s.top()<<endl;
s.pop();
return 0;
}