题目描述
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入 Copy
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
样例输出 Copy
12178.21
#include <cstdio>
#include <stack>
bool isJC(char ch) {
return ch == '+' || ch == '-';
}
bool isCC(char ch) {
return ch == '*' || ch == '/';
}
bool isOp(char ch) {
return isCC(ch) || isJC(ch);
}
bool isSpace(char ch) {
return ch == ' ';
}
bool isNum(char ch) {
return '0' <= ch && ch <= '9';
}
bool isBig(char ch1, char ch2) {
return isJC(ch1) && isCC(ch2);
}
double evalVal(double num1, double num2, char op) {
if (op == '+') {
return num1 + num2;
} else if (op == '-') {
return num1 - num2;
} else if (op == '*') {
return num1 * num2;
} else if (op == '/') {
return num1 / num2;
}
return 0;
}
char str[205];
std::stack<double> nums;
std::stack<char> ops;
void func() {
int idx = 0;
int tmpNum;
double tmpNum1, tmpNum2;
while (str[idx] != '\0') {
if (isNum(str[idx])) {
tmpNum = str[idx] - '0';
idx++;
while (str[idx] != '\0' && isNum(str[idx])) {
tmpNum = tmpNum * 10 + str[idx] - '0';
idx++;
}
nums.push(tmpNum);
} else if (isSpace(str[idx])) {
idx++;
} else if (isOp(str[idx])) {
while (!ops.empty() && !isBig(ops.top(), str[idx])) {
tmpNum2 = nums.top();
nums.pop();
tmpNum1 = nums.top();
nums.pop();
nums.push(evalVal(tmpNum1, tmpNum2, ops.top()));
ops.pop();
}
ops.push(str[idx]);
idx++;
}
}
while (!ops.empty()) {
tmpNum2 = nums.top();
nums.pop();
tmpNum1 = nums.top();
nums.pop();
nums.push(evalVal(tmpNum1, tmpNum2, ops.top()));
ops.pop();
}
printf("%.2f\n", nums.top());
}
int main() {
scanf("%[^\n]", str);
getchar();
while (true) {
if (str[0] == '0' && str[1] == '\0') {
break;
}
func();
scanf("%[^\n]", str);
getchar();
}
return 0;
}