64,654
社区成员
发帖
与我相关
我的任务
分享
E→E+T|E-T|T
T→T*F| T/F|F
F→(E)|i
#include<stdio.h>
#include<string>
using namespace std;
int pos = 0;
string str = "1+2*3-4";
double E();
double T();
double F();
int main() {
double v = E();
printf("%f", v);
getchar();
return 0;
}
double E() {
double v = 0;
char c = str.at(pos);
if (c == '+') {
pos++;
v = E() + T();
}
else if (c == '+') {
pos++;
v = E() - T();
}
else {
pos++;
v = T();
}
return v;
}
double T() {
double v = 0;
char c = str.at(pos);
if (c == '*') {
pos++;
v = T() * F();
}
else if (c == '/') {
pos++;
v = T() / F();
}
else {
pos++;
v = F();
}
return v;
}
double F() {
char c = str.at(pos);
if (c == '(') {
pos++;
double v = E();
c = str.at(pos);
if (c == ')') {
pos++;
return v;
}
}
else {
string s = "";
while (true) {
c = str.at(pos);
if (c >= '0' && c <= '9') {
s += c;
pos++;
}
else {
break;
}
}
return atoi(s.c_str());
}
return 0;
}