题目描述
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92 0
样例输出
12178.21
//问题 A: 简单计算器
/*题目描述
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
样例输入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
*/
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<map>
using namespace std;
struct node//将数字和运算符看作一个节点,用flag区分
{
double num;
char op;
bool flag;//1 为操作数 0为操作符
};
string str;//中缀表达式
stack<node> s;//操作符栈
queue<node> q;//后缀表达式
map<char,int> opm;//操作符优先级
//step 1: 中缀表达式转后缀表达式(不需要用括号就能表示出整个表达式哪部分运算先进行)
void change()
{
node temp;
for(int i=0;i<str.length();)//扫描infix
{
if(str[i]>='0'&&str[i]<='9')
{
temp.flag=1;//标记为数字
temp.num=str[i++]-'0';
while(i<str.length() && str[i]>='0' && str[i]<='9')//后续仍是数字且不超过长度
{
temp.num=temp.num*10+(str[i]-'0');
i++;
}
q.push(temp);//操作数进入后缀序列
}
else
{
temp.flag=0;//标记为运算符
while(!s.empty() && opm[str[i]]<=opm[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();
}
}
//step 2: 计算后缀表达式
double result()
{
double a,b;
node temp,result;
while(!q.empty())
{
temp=q.front();
q.pop();
if(temp.flag ==1)
{
s.push(temp);
}
else
{
b=s.top().num;
s.pop();
a=s.top().num;
s.pop();
result.flag =1;
if(temp.op=='+') result.num =a+b;
else if(temp.op=='-') result.num =a-b;
else if(temp.op=='*') result.num =a*b;
else if(temp.op=='/') result.num =a/b;
s.push(result);
}
}
return s.top().num ;
}
int main()
{
opm['+']=opm['-']=1;
opm['*']=opm['/']=2;
while(getline(cin,str),str!="0")//案例为0时结束
{
for(string::iterator it=str.begin();it!=str.end();it++)//去除整数和运算符之间空格
{
if(*it==' ')
{
str.erase(it);
}
}
while(!s.empty()) {s.pop();}//初始化栈
change();
printf("%.2f\n",result());//表达式的值,精确到小数点后2位
}
return 0;
}