/*
题目描述:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 2
4 + 2 * 5 - 7 / 11
0
样例输出:
3.00
13.36
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cctype>
#include <stack>
#include <cstdlib>
#include <map>
#include <utility>
using namespace std;
int main()
{
string str;
map<char, int> opPriority;
double a, b;
opPriority.insert(pair<char, int>('+', 0));
opPriority.insert(pair<char, int>('-', 0));
opPriority.insert(pair<char, int>('*', 1));
opPriority.insert(pair<char, int>('/', 1));
#ifndef ONLINE_JUDGE
ifstream cin("d:\\OJ\\uva_in.txt");
#endif // ONLINE_JUDGE
while (getline(cin, str)) {
if (str == "0")
break;
istringstream line(str);
string tmp;
stack<double> s;
stack<char> op;
while (line >> tmp) {
if (isdigit(tmp[0])) {
s.push(atof(tmp.c_str()));
} else {
if (op.empty())
op.push(tmp[0]);
else {
char ch = tmp[0];
char stackch = op.top();
while (!op.empty() && opPriority[ch] <= opPriority[stackch]) {
op.pop();
if (stackch == '+') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = a + b;
s.push(a);
} else if (stackch == '-') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = b - a;
//cout << "a:" << a <<endl;
s.push(a);
} else if (stackch == '*') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = a * b;
s.push(a);
} else if (stackch == '/') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = b / a;
s.push(a);
}
if (!op.empty())
stackch = op.top();
}
op.push(ch);
}
}
}
while (!op.empty()) {
char stackch = op.top();
op.pop();
if (stackch == '+') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = a + b;
s.push(a);
} else if (stackch == '-') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = b - a;
s.push(a);
} else if (stackch == '*') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = a * b;
s.push(a);
} else if (stackch == '/') {
a = s.top();
s.pop();
b = s.top();
s.pop();
a = b / a;
s.push(a);
}
}
double ans = s.top();
s.pop();
cout.precision(2);
cout << fixed << ans <<endl;
}
return 0;
}
题目1019:简单计算器
最新推荐文章于 2021-03-11 23:00:37 发布