repl.it
@AllenLi1/

Expression

C++

No description

fork
loading
Files
  • main.cpp
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
#include <cctype>
#include <cstdlib>
#include <map>
#include <cmath>

using namespace std;

stack <double> num;
stack <char> sym;
map <char, int> p;
string s;

double calc(double a, double b, char c) {
  if (c == '+') return a + b;
  if (c == '-') return a - b;
  if (c == '/') return a / b;
  if (c == '*') return a * b;
  if (c == '^') return pow(a, b);
  return 0;
}

int main() {
  getline(cin, s);
  s = '(' + s + ')';
  p['('] = 0;
  p['+'] = 1;
  p['-'] = 1;
  p['*'] = 2;
  p['/'] = 2;
  p['^'] = 3;
  int now = 0;
  double ret;
  while (now < s.size()) {
    if (isspace(s[now])) {
      ++now;
      continue;
    }
    ret = 0;
    if (isdigit(s[now])) {  // number
      while (isdigit(s[now])) {  // decimal
        ret = ret * 10 + s[now] - 48;
        ++now;
      }
      if (s[now] == '.') {  // fraction
        ++now;
        double xiao = 0;
        double wei = 0.1;
        while (isdigit(s[now])) {
          xiao = xiao + wei * (s[now] - 48);
          wei /= 10;
          ++now;
        }
        ret += xiao;
      }
      num.push(ret);

    } else {
      if (isspace(s[now])) {
        ++now;
        continue;
      }
      if (s[now] == '(') {
        sym.push('(');
        ++now;
        continue;
      }
      if (s[now] == ')') {
        while (sym.top() != '(') {
          double a = num.top();
          num.pop();
          double b = num.top();
          num.pop();
          num.push(calc(b, a, sym.top()));
          sym.pop();
        }
        sym.pop();
      } else {
        while (p[s[now]] <= p[sym.top()]) {
          double a = num.top();
          num.pop();
          double b = num.top();
          num.pop();
          num.push(calc(b, a, sym.top()));
          sym.pop();
        }
        sym.push(s[now]);
      }
      ++now;
    }
  }
  cout.precision(3);
  cout << fixed << num.top();
  return 0;
}
Fetching token
?