| 135 | |
| 136 | return output; |
| 137 | } |
| 138 | |
| 139 | private static evaluatePostfix(postfix: string[]): number { |
| 140 | const stack: number[] = []; |
| 141 | |
| 142 | for (const token of postfix) { |
| 143 | if (this.isNumber(token)) { |
| 144 | stack.push(parseFloat(token)); |
| 145 | continue; |
| 146 | } |
| 147 | |
| 148 | if (!(token in this.operators)) { |
| 149 | throw new Error(`未知操作符: ${token}`); |
| 150 | } |
| 151 | |
| 152 | if (stack.length < 2) { |
| 153 | throw new Error("表达式格式错误"); |
| 154 | } |
| 155 | |
| 156 | const b = stack.pop()!; |
| 157 | const a = stack.pop()!; |
| 158 | |
| 159 | let result: number; |
| 160 | switch (token) { |
| 161 | case "+": |
| 162 | result = a + b; |
| 163 | break; |
| 164 | case "-": |
| 165 | result = a - b; |
| 166 | break; |
| 167 | case "*": |
| 168 | result = a * b; |
| 169 | break; |
| 170 | case "/": |
| 171 | if (b === 0) { |
| 172 | throw new Error("除零错误"); |
| 173 | } |
| 174 | result = a / b; |
| 175 | break; |
| 176 | default: |
| 177 | throw new Error(`未知操作符: ${token}`); |
| 178 | } |
| 179 | |
| 180 | stack.push(result); |
| 181 | } |
| 182 | |
| 183 | if (stack.length !== 1) { |
| 184 | throw new Error("表达式格式错误"); |
| 185 | } |
| 186 | |
| 187 | return stack[0]; |
| 188 | } |
| 189 | |