题目29:计算表达式

来源:互联网 发布:w7upnp nat端口失败 编辑:程序博客网 时间:2024/05/21 08:05
题目描述:
对于一个不存在括号的表达式进行计算
输入:
存在多种数据,每组数据一行,表达式不存在空格
输出:
输出结果
样例输入:
6/2+3+3*4
样例输出:

18

#include <stdio.h> #include <stack> #include <string.h> #include <cctype> using namespace std;  int pri[5][5] = { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 }, { 1,     1, 1, 0, 0 }, { 1, 1, 1, 0, 0 } };//定义操作符优先级 stack<double> s; stack<int> op;  int find(char c) {     switch (c) {     case '#':         return 0;     case '+':         return 1;     case '-':         return 2;     case '*':         return 3;     case '/':         return 4;     } }  int main() {     char st[101], *p;     double r, x, y, tmp;     int c, a;     while (~scanf("%s",st)) {    //换成gets(st)将bug,具体原因不是很清楚,我猜测可能是与我用*p有关,现在还是新手解释不了         int len = strlen(st);             st[len++] = '#';         st[len] = 0;         op.push(0);         p = st;         while (*p) {             a = *p++ - '0';             while (isdigit(*p))                 a = 10 * a +  *p++ - '0';//获取操作数             s.push((double)a);             while (!pri[find(*p)][op.top()] && op.size() >= 2) {                 x = s.top();                 s.pop();                 y = s.top();                 s.pop();                 c = op.top();                 op.pop();                 if (c == 1)                     tmp = x + y;                 else if (c == 2)                     tmp = y - x;                 else if (c == 3)                     tmp = x * y;                 else if (c == 4)                     tmp = y / x;                 s.push(tmp);             }             op.push(find(*p++));             if (op.size() == 2 && !op.top()) {                 printf("%.lf\n", s.top());                 s.pop();op.pop();op.pop();                 break;             }         }     }     return 0; }