計算帶有括號的表達式的值
阿新 • • 發佈:2019-03-09
namespace clas () oot end main mes else char
關鍵在於尋找括號
#include<cstdio> #include<cstring> using namespace std; const int maxn = 100; char s[maxn]; int left[maxn],right[maxn]; char node[maxn]; int cnt = 0; int newnode() { cnt++; left[cnt] = 0; right[cnt] = 0; return cnt; } int creat_tree(int start,intend) { int p = 0,c1 = -1,c2 = -1; if(end - start == 1) { int u = newnode(); node[u] = s[start]; return u; } for(int i = start;i < end;i++) { if(s[i] == ‘(‘) p++; else if(s[i] == ‘)‘) p--;else if((s[i] == ‘+‘ || s[i] == ‘-‘) && !p)//加減號,且不在括號裏面 { c1 = i; } else if((s[i] == ‘*‘ || s[i] == ‘/‘) && !p) { c2 = i; } } if(c1 == -1 && c2 == -1)//都在括號裏面 { return creat_tree(start + 1,end - 1); } else if(c1 != -1)//最右面的加減號 { int u = newnode(); node[u] = s[c1]; left[u] = creat_tree(start,c1); right[u] = creat_tree(c1 + 1,end); return u; } else { int u = newnode(); node[u] = s[c2]; left[u] = creat_tree(start,c2); right[u] = creat_tree(c2 + 1,end); return u; } } double comput(int root) { if(node[root] == ‘*‘) { return comput(left[root]) * comput(right[root]); } if(node[root] == ‘/‘) { return comput(left[root]) / comput(right[root]); } if(node[root] == ‘-‘) { return comput(left[root]) - comput(right[root]); } if(node[root] == ‘+‘) { return comput(left[root]) + comput(right[root]); } return (double)node[root] - ‘0‘; } int main() { freopen("input.txt","r",stdin); scanf("%s",s); int root = creat_tree(0,strlen(s)); double result = comput(root); return 0; }
計算帶有括號的表達式的值