读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
核心考点:栈的使用。
思路:因为运算有优先级,所以在刚开始先考虑乘除。
如果当前数字前面的运算符是 “+”,则直接把数压入栈里,
如果是减法,则把数的相反数压入栈里,
如果是乘法,则取栈头的数相乘,并 pop() 出栈头,后把相乘结果 push() 进栈,
除法和乘法方法一样
代码:
#include <stack>
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main() {
stack<double>shu;
string a;
while (getline(cin,a)&&a!="0") {
int flag=1,tmp=0;
for (int i = 0; i < a.length(); i++) {
if (a[i] == ' ')continue;
else if (a[i] == '+') flag = 1;
else if (a[i] == '-') flag = 2;
else if (a[i] == '*') flag = 3;
else if (a[i] == '/') flag = 4;
else{
tmp = 0;
while (a[i] >= '0' && a[i] <= '9') {
tmp = tmp * 10 + (a[i] - '0'); i++;
}
i--;
switch (flag) {
case 1: shu.push(tmp); break;
case 2: shu.push(-tmp); break;
case 3: {
double x = shu.top() * tmp; shu.pop();
shu.push(x);
break;
}
case 4: {
double x = shu.top() / tmp; shu.pop();
shu.push(x);
break;
}
}
}
}
double ans = 0;
while (!shu.empty()) {
ans += shu.top(); shu.pop();
}
cout <<setprecision(2)<<fixed<< ans << endl;
}
}