问题 A: 简单计算器
[命题人 : 外部导入]
时间限制 : 1.000 sec 内存限制 : 32 MB
题目描述
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入 Copy
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
样例输出 Copy
12178.21
提示:
中缀表达式转后缀表达式:
1、设立一个操作符栈s,用来暂时存放操作符;设立一个数组或者队列q,用来存放后缀表达式;
2、从左往右扫描中缀表达式,如果遇到操作数(操作数若为多位,则需要累加合并在一块,再入队),则将操作数加入后缀表达式。
3、如果遇到操作符op,将操作符op与此时操作符栈s的栈顶的操作符,进行比较:
若op的优先级高于栈顶操作符的优先级,则压入操作符栈s;
若op的优先级小于或者等于栈顶操作符的优先级,则将操作符栈从栈顶开始扫描,出栈加入后缀表达式,直到op的优先级大于栈中的操作符的优先级;
4、重复上述操作,若中缀表达式扫描结束,将操作符栈剩下的操作符依次出栈,按出栈顺序加入至后缀表达式;
后缀表达式求值:
从左往右扫描后缀表达式,若是操作数,则入数栈;若是操作符,则从数栈中连续弹出两个操作数,按照操作符,进行运算(后出栈的为第一操作数,先出栈的为第二操作数),将运算结果加入数栈。直至后缀表达式扫描完毕,数栈中此时只会存一个数,改数即为结果。
AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<cctype>
#include<set>
#include<queue>
#include<stack>
using namespace std;
/*
测试数据
1 + 3 * 5 / 4 * 8 / 9 * 6 * 2 / 3 / 7 + 3 * 8 / 2 //14.90
2 * 3 / 49 //0.12
5 + 2 * 3 / 49 - 4 /13 //4.81
*/
struct node
{
double num;//操作数
char op;//操作符
int flag;//1表示操作数 0表示操作符
};
string str;
queue<node>q;//后缀表达式队列
stack<node>s;//操作符栈
map<char,int> op;
void change()
{
int dit=0;
for(int i=0; i<str.length(); i++)
{
node t;
dit=0;
if(str[i]>='0'&&str[i]<='9')
{
dit=str[i]-'0';
i++;
while(str[i]>='0'&&str[i]<='9')
{
dit=dit*10+str[i]-'0';
i++;
}
t.num=dit;
t.flag=1;
q.push(t);
i--;
}
else
{
t.flag=0;
t.op=str[i];
while(!s.empty()&&op[s.top().op]>=op[t.op])
{
q.push(s.top());
s.pop();
}
s.push(t);
}
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
}
void cal()
{
while(!q.empty())
{
if(q.front().flag==1)
{
s.push(q.front());
q.pop();
}
else
{
double x,y;
y=s.top().num;
s.pop();
x=s.top().num;
s.pop();
node t;
if(q.front().op=='/')
x=x/y;
else if(q.front().op=='*')
x=x*y;
else if(q.front().op=='+')
x=x+y;
else if(q.front().op=='-')
x=x-y;
t.flag=1;
t.num=x;
s.push(t);
q.pop();
}
}
printf("%.2lf\n",s.top().num);
}
int main()
{
op['/']=op['*']=2;
op['-']=op['+']=1;
while(getline(cin,str))
{
if(str.length()==1&&str[0]=='0')
break;
for(string::iterator it=str.begin(); it!=str.end(); it++)//将空格去掉
if(*it==' ')
str.erase(it);
// cout<<s<<endl;
change();//将中缀表达式转化为后缀表达式
cal();//后缀表达式求值
while(!q.empty())
{
q.pop();
}
while(!s.empty())
{
s.pop();
}
}
return 0;
}