版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34302921/article/details/81048203
晚上做PAT半个小时没有把失去的3分找回来(17 / 20), 转去刷codeup, 这个OJ和PAT有一些不同,它进行的是多点测试,难度要大于PAT,没有烦人的PAT格式要求,可以把更多的精力放在算法本身。
下面是[codeup 1918]简单计算器的题目,对于四则运算,主要就是两步,中缀表达式转换为后缀表达式,后缀表达式求值。这属于数据结构中stack和queue的应用。为了把更多的精力放在算法实现,直接调用了C++ STL中的queue和stack。
如果对算法原理不懂,百度一下原理满天飞,耐心看完一篇博客就懂了……这里不再赘述。
#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
#include<queue>
#include<map>
using namespace std;
//抽象操作数和操作符,代价是消耗内存
typedef struct Node
{
double num; //操作数
char op; //操作符
bool flag; //操作数true, 操作符false
}Node;
string str; //获取计算表达式
stack<Node> s; //操作符栈
queue<Node> q; //后缀表达式序列
map<char, int> op;
void change()
{
double num;
Node tmp;
for(int i = 0; i < str.length(); )
{
if(str[i] >= '0' && str[i] <= '9')
{
tmp.flag = true;
tmp.num = str[i++] - '0';
while(i < str.length() && str[i] <= '9' && str[i] >= '0')
tmp.num = tmp.num * 10 + str[i++] - '0';
q.push(tmp);
}
else
{
tmp.flag = false;
while(!s.empty() && op[s.top().op] >= op[str[i]])
{
q.push(s.top());
s.pop();
}
tmp.op = str[i];
s.push(tmp);
++i;
}
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
}
double calc()
{
Node tmp, cur;
while(!q.empty())
{
tmp = q.front();
q.pop();
if(tmp.flag)
{
s.push(tmp);
}
else
{
double num1, num2, res;
num2 = s.top().num;
s.pop();
num1 = s.top().num;
s.pop();
switch(tmp.op)
{
case '+' :
res = num1 + num2;
break;
case '-' :
res = num1 - num2;
break;
case '*' :
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
break;
}
cur.num = res;
cur.flag = true;
s.push(cur);
}
}
return s.top().num;
}
int main()
{
op['+'] = op['-'] = 1;
op['*'] = op['/'] = 2;
while(getline(cin, str), str != "0")
{
//去除输入的空格
for(string::iterator it = str.end(); it != str.begin(); --it)
{
if(*it == ' ')
str.erase(it);
}
//初始化操作符栈
while(!s.empty())
s.pop();
//中缀表达式转换为后缀表达式
change();
printf("%.2f", calc());
}
return 0;
}