-
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
-
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
-
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
-
1 + 2 4 + 2 * 5 - 7 / 11 0
-
3.00 13.36
题目描述:
-
输入:
-
输出:
-
样例输入:
-
样例输出:
采用两个栈分别记录数字和操作符的方法,根据规则来决定操作符的压栈弹栈
未能处理好最后仅剩加减法的部分,暂时未能AC
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <cstring>
#include <vector>
using namespace std;
double calculate(double a, double b, char op)
{
double ans;
switch(op) {
case '+':
ans = a + b;
break;
case '-':
ans = a - b;
break;
case '*':
ans = a * b;
break;
case '/':
ans = a / b;
break;
}
return ans;
}
int main() {
vector<double> stk1;
vector<char> stk2;
char str[200];
int i;
while (gets(str)) {
if (str[0] == '0' && strlen(str) == 1)
break;
while (!stk1.empty())
stk1.pop_back();
while (!stk2.empty())
stk2.pop_back();
for (i = 0; i < strlen(str); i++) {
if (str[i] >= '0' && str[i] <= '9') {
int temp = 0;
temp += str[i] - '0';
while (str[i+1] != ' ' && str[i+1] != '\0') {
i++;
temp *= 10;
temp += str[i] - '0';
}
stk1.push_back(temp*1.0);
}
else if (str[i] == '+' || str[i] == '-') {
if (stk2.empty())
stk2.push_back(str[i]);
else if (stk2.back() == '+' || stk2.back() == '-')
stk2.push_back(str[i]);
else if (stk2.back() == '*' || stk2.back() == '/') {
double a = stk1.back();
stk1.pop_back();
double b = stk1.back();
stk1.pop_back();
char op = stk2.back();
stk2.pop_back();
double ans = calculate(b, a, op);
stk1.push_back(ans);
stk2.push_back(str[i]);
}
}
else if (str[i] == '*' || str[i] == '/') {
if (stk2.back() != '*' && stk2.back() != '/')
stk2.push_back(str[i]);
else {
double a = stk1.back();
stk1.pop_back();
double b = stk1.back();
stk1.pop_back();
char op = stk2.back();
stk2.pop_back();
double ans = calculate(b, a, op);
stk1.push_back(ans);
stk2.push_back(str[i]);
}
}
}
vector<double>::iterator iter1 = stk1.begin();
vector<char>::iterator iter2 = stk2.begin();
while (!stk2.empty()) {
double a = *iter1;
stk1.erase(iter1);
double b = *iter1;
stk1.erase(iter1);
char op = *iter2;
stk2.erase(iter2);
double ans = calculate(b, a, op);
}
printf("%.2f\n", *iter1);
}
return 0;
}