要求: 给一个只含+、-、*、/、(、)这6个字符的合法表达式,计算表达式的值
Code:
#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
queue<char> q;
double expresion_cal();
double term_cal();
double factor_cal();
double expresion_cal() {
double res = term_cal();//获取+和-的左操作数
while (true && !q.empty()) {
char op = q.front();
if (op == '+' || op == '-') {
q.pop();
double val = term_cal();
if (op == '+')
res += val;
else
res -= val;
} else {
break;
}
}
return res;
}
double term_cal () {
double res = factor_cal();//获取*和/的左操作数
while (true && !q.empty()) {
char op = q.front();
if (op == '*' || op == '/') {
q.pop();
double val = term_cal();
if (op == '*')
res *= val;
else
res /= val;
} else {
break;
}
}
return res;
}
double factor_cal () {
double res = 0;
char cc = q.front();
if (cc == '(') {
q.pop();
res = expresion_cal();
q.pop();
} else {
while (isdigit(cc)) {
res = res * 10 + cc - '0';
q.pop();
cc = q.front();
}
if (cc == '.') {
double t = 0.1;
q.pop();
cc = q.front();
while (isdigit(cc)) {
res += t*(cc - '0');
t *= 0.1;
q.pop();
cc = q.front();
}
}
}
return res;
}
int main()
{
string s;
while (cin>>s) {
for (int i=0;i<s.length();i++)
q.push(s[i]);
printf("%lf\n", expresion_cal());
}
return 0;
}
ps: 之前写了个java的,再换个c++来(水一下 )记录一下