读入一个只包含+,-,*,/ 的非负整数计算表达式,计算该表达式的值
思路:给出一个中缀表达式然后转成后缀表达式,用一个栈来存操作符,队列存后缀表达式,最后计算后缀表达式。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include <vector>
#include<stack>
#include <queue>
#include<map>
#include<iostream>
#include <functional>
#define MAX 1001
#define MAXD 6
#define TELNUM 10
using namespace std;
struct node{
double num;
char op;
bool flag;
};
string str;
stack<node> s;
queue<node> q;
map<char,int> op;
void change()
{
node temp;
double num;
for(int i = 0; i < str.size();)
{
if(str[i] >= '0' && str[i] <= '9')
{
temp.flag = true;
temp.num = str[i++] - '0';
while(i < str.size() && str[i] >= '0' && str[i] <= '9')
{
temp.num = temp.num * 10 + (str[i] - '0');
i++;
}
q.push(temp);
}
else
{
temp.flag = false;
while(!s.empty() && op[str[i]] <= op[s.top().op])/*当栈顶的操作符优先级大于当前操作符,就将栈中的操作符弹出到队列中,
直到栈顶操作符优先级小于等于当前操作符,或者栈为空*/
{
q.push(s.top());
s.pop();
}
temp.op = str[i];
s.push(temp);
i++;
}
}
while(!s.empty())/*将剩余的操作符全部弹入到队列中*/
{
q.push(s.top());
s.pop();
}
}
double cal()
{
double temp1,temp2;
node cur,temp;
while(!q.empty())
{
cur = q.front();/*指向队列头位置*/
q.pop();
if(cur.flag == true)
{
s.push(cur);/*是数字就压入栈中*/
}
else
{
temp2 = s.top().num;
s.pop();
temp1 = s.top().num;
s.pop();
temp.flag = true;
if(cur.op == '+') temp.num = temp1 + temp2;
else if(cur.op == '-') temp.num = temp1 - temp2;
else if(cur.op == '*') temp.num = temp1 * temp2;
else if(cur.op == '/') temp.num = temp1 / temp2;
s.push(temp);/*把该次计算的值压入栈中*/
}
}
return s.top().num;/*最后栈顶的元素就是后缀表达式的值*/
}
int main(void)
{
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\n",cal());
}
}