天天看點

CSU 1655 文本電腦

Description

Bob讨厭複雜的數學運算.

看到練習冊上的算術題,Bob很是頭痛.

為了完成作業,Bob想要你幫忙寫一個文本版的四則運算電腦.

這個電腦的功能需求十分簡單,隻要可以處理加減乘除和括号就可以了.

你能夠幫助Bob嗎?

Input

每個樣例一行,輸入一個長度小于1500的包含有'(',')','+','-','*','/',和'1'~'9'組成的四則運算表達式.

對于每個樣例,參與運算數字在0~10000之間,表達式運算的結果在double的表示範圍内.

Output

對于每一個例子,輸出表達式的計算結果,精确到小數點後4位

Sample Input

3928*3180*3229+2137
2477*8638
1535+7452+3780+2061*280/3070/(7828-9348)      
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
const int maxn = 100005;
char s[maxn];

int main()
{
  while (scanf("%s", s) != EOF)
  {
    stack<double> p;
    stack<char> d;
    for (int i = 0; s[i]; i++)
    {
      if (s[i] >= '0'&&s[i] <= '9')
      {
        double u = 0;
        while (s[i] >= '0'&&s[i] <= '9') u = u * 10 + s[i++] - '0';
        p.push(u);  i--;
      }
      else
      {
        if (d.empty() || s[i] == '(') d.push(s[i]);
        else
        {
          if (s[i] == ')')
          {
            while (d.top() != '(')
            {
              double x = p.top(); p.pop();
              double y = p.top(); p.pop();
              if (d.top() == '*') p.push(y * x);
              if (d.top() == '/') p.push(y / x);
              if (d.top() == '+') p.push(y + x);
              if (d.top() == '-') p.push(y - x);
              d.pop();
            }
            d.pop();
          }
          else
          {
            if (d.top() != '(')
            if (s[i] == '+' || s[i] == '-')
            {
              while (!d.empty() && d.top() != '(')
              {
                double x = p.top(); p.pop();
                double y = p.top(); p.pop();
                if (d.top() == '*') p.push(y * x);
                if (d.top() == '/') p.push(y / x);
                if (d.top() == '+') p.push(y + x);
                if (d.top() == '-') p.push(y - x);
                d.pop();
              }
            }
            else if (d.top() == '*' || d.top() == '/')
            {
              double x = p.top(); p.pop();
              double y = p.top(); p.pop();
              if (d.top() == '*') p.push(y * x);
              if (d.top() == '/') p.push(y / x);
              if (d.top() == '+') p.push(y + x);
              if (d.top() == '-') p.push(y - x);
              d.pop();
            }
            d.push(s[i]);
          }
        }
      }
    }
    while (!d.empty())
    {
      double x = p.top(); p.pop();
      double y = p.top(); p.pop();
      if (d.top() == '*') p.push(y * x);
      if (d.top() == '/') p.push(y / x);
      if (d.top() == '+') p.push(y + x);
      if (d.top() == '-') p.push(y - x);
      d.pop();
    }
    printf("%.4lf\n", p.top());
  }
  return 0;
}