Problem Description:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input:
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output:
3.00
13.36
题解:
#include<bits/stdc++.h>
using namespace std;
map<char, int> mp;
stack<double> num;
stack<char> ope;
double strToDou(string s) {
stringstream ss;
ss<<s;
double n;
ss>>n;
return n;
}
void process(char tmp) {
while(!ope.empty() && mp[ope.top()]>=mp[tmp]) {
double a2 = num.top();
num.pop();
double a1 = num.top();
num.pop();
char op = ope.top();
ope.pop();
double ans = 0;
if(op=='+') {
ans = a1+a2;
}
if(op=='-') {
ans = a1-a2;
}
if(op=='*') {
ans = a1*a2;
}
if(op=='/') {
ans = a1/a2;
}
num.push(ans);
}
if(tmp!='!') {
ope.push(tmp);
}
}
int main() {
mp['+'] = 1;
mp['-'] = 1;
mp['*'] = 2;
mp['/'] = 2;
string s;
getline(cin, s);
while(s.compare("0")) {
//初始化,清空操作数栈和运算符栈
while(!num.empty()) {
num.pop();
}
while(!ope.empty()) {
ope.pop();
}
//遍历输入字符串
while(s.find(" ")!=-1) {
string tmp = s.substr(0, s.find(" "));
s = s.substr(s.find(" ")+1);
if(tmp.at(0)=='+' || tmp.at(0)=='-' || tmp.at(0)=='*' || tmp.at(0)=='/') {
if(ope.empty() || mp[ope.top()]<mp[tmp.at(0)]) {
ope.push(tmp.at(0));
} else {
process(tmp.at(0));
}
} else {
double n = strToDou(tmp);
num.push(n);
}
}
//把最后一个运算数放入栈中
double last = strToDou(s);
num.push(last);
//处理最后一个表达式直到结束
if(ope.size()) {
process('!');
}
printf("%.2lf\n", num.top());
getline(cin, s);
}
return 0;
}