构建树并计算算术表达式(为了应付该作业,仅供参考)
只是应付数据结构老师分配。式中的号码只能是一个整数:
例如,输入 (6+3)*(4-2)*(41-1)
出口 720.00
#include <stdio.h> #include <string.h> const int N = 1000; int m[N], flag; double res; struct Node { double val; char c; Node* left; Node* right; Node() { left = right = NULL; c = 'a' - 1; } }; Node* build(char *str, int l, int r) { int flag1 = -1, flag2 = -1, p = 0; Node* node = new Node; if (r - l == 1) { node -> val = m[str[l]]; return node; } for (int i = l; i < r; i++) { switch(str[i]) { case '(' : p++; break; case ')' : p--; break; case '+' : case '-' : if (!p) flag1 = i; break; case '*' : case '/' : if (!p) flag2 = i; break; } } if (flag1 < 0) flag1 = flag2; if (flag1 < 0) return build(str, l + 1, r - 1); node -> left = build(str, l, flag1); node -> right = build(str, flag1 + 1, r); node -> c = str[flag1]; return node; } double preOrder(Node* root) { if (root == NULL) return 0; if (root -> c == 'a' - 1) return root -> val; double a; switch(root -> c) { case '+': a = preOrder(root -> left) + preOrder(root -> right); break; case '-': a = preOrder(root -> left) - preOrder(root -> right); break; case '*': a = preOrder(root -> left) * preOrder(root -> right); break; case '/': if (preOrder(root -> right) != 0) a = preOrder(root -> left) / preOrder(root -> right); else flag = 1; break; } return a; } int main() { Node* root; char str[N], s[N]; while (scanf("%s", str) != EOF) { memset(m, 0, sizeof(m)); res = flag = 0; int len = strlen(str); int n = 0; char a = 'a'; if (str[0] == '-') s[n++] = a++; for (int i = 0; i < len; i++) { if (str[i] > '9' || str[i] < '0') s[n++] = str[i]; else { int sum = 0; while (str[i] >= '0' && str[i] <= '9') { sum = sum * 10 + str[i] - '0'; i++; } i--; m[a] = sum; s[n++] = a++; } } s[n] = '\0'; root = build(s, 0, n); res = preOrder(root); if (!flag) printf("表达式结果: %.2lf\n", res); else printf("error!\n"); } return 0; }
版权声明:本文博客原创文章,博客,未经同意,不得转载。