周鸿博 2020-04-05 13:00:06 2020-04-05 13:05:12
1.3.2.4 <<表达式求值(易)>>有谁会??? 1.3.2.5 <<表达式求值(极易)>>我会. 但不会1.3.2.4...... 求大神指导. 急!
#include <cstdio> const int MAX = 100001; int stack[MAX / 2] = { 0 }; char abcd[MAX] = { 0 }, strsta[MAX / 2] = { 0 }; int len = 0, lens = 0, lenr = 0; int main() { int tmp = 0; char c = getchar(); while (c != '\n') { abcd[len++] = c; c = getchar(); } for (int i = 0; i < len; i++) { if (abcd[i] >= '0' && abcd[i] <= '9') { tmp *= 10; tmp += abcd[i] - '0'; } else { if (abcd[i - 1] != ')') stack[lens++] = tmp; tmp = 0; strsta[lenr++] = abcd[i]; if (abcd[i] == ')') { int j = lenr - 1; while (strsta[j] != '(') j--; if (strsta[lenr - 2] == '*') { stack[lens - 2] *= stack[lens - 1]; lens--; } if (strsta[lenr - 2] == '/') { if (stack[lens - 1] == 0) { printf("div0."); return 0; } stack[lens - 2] /= stack[lens - 1]; lens--; } stack[j] = stack[j + 1]; for (int k = j + 1; k < lenr - 1; k++) { if (strsta[k] == '+') stack[j] += stack[k + 1]; if (strsta[k] == '-') stack[j] -= stack[k + 1]; strsta[k] = stack[k + 1] = 0; } strsta[j] = 0; lenr = j; lens = j + 1; } } if (i == len - 1 && abcd[i] <= '9' && abcd[i] >= '0') stack[lens++] = tmp; if (strsta[lenr - 2] == '*' && strsta[lenr - 1] != '(') { stack[lens - 2] *= stack[lens - 1]; strsta[lenr - 2] = strsta[lenr - 1]; lens--; lenr--; } if (strsta[lenr - 2] == '/' && strsta[lenr - 1] != '(') { if (stack[lens - 1] == 0) { printf("div0."); return 0; } stack[lens - 2] /= stack[lens - 1]; strsta[lenr - 2] = strsta[lenr - 1]; lens--; lenr--; } } if (strsta[lenr - 1] == '*') { stack[lens - 2] *= stack[lens - 1]; lens--; } if (strsta[lenr - 1] == '/') { if (stack[lens - 1] == 0) { printf("div0."); return 0; } stack[lens - 2] /= stack[lens - 1]; lens--; } for (int i = 0; i < lens; i++) { if (strsta[i] == '+') stack[0] += stack[i + 1]; if (strsta[i] == '-') stack[0] -= stack[i + 1]; } printf("%d", stack[0]); return 0; }
此乃解题大法也
额
共 3 条回复
额