Skip to content

Commit 10fc4ea

Browse files
author
汤杨
committed
wip: 修改为仅支持任意数量的乘除法
1 parent 0827409 commit 10fc4ea

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

part_3/calc.cpp

+13-8
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
/**
2+
* 1. 绘制乘法和除法的语法图
3+
* 2. 修改源码使之支持任意数量 term 的只包含乘除法的表达式
4+
* 3. 使用任意你喜欢的语言来从头实现支持任意数量加减法表达式的解释器
5+
*/
16
#include <iostream>
27
#include <string>
38
#include <exception>
@@ -112,18 +117,18 @@ class Interpreter {
112117
public:
113118
explicit Interpreter(std::string text) : _text(std::move(text)), _current_char(_text[0]) {}
114119

115-
// 语法分析器(parser)仅能处理正整数的加减法
120+
// 语法分析器(parser)仅能处理正整数的乘除法
116121
double expr() {
117122
_current_token = getNextToken();
118123
double result = getTerm();
119-
while (_current_token._type == PLUS or _current_token._type == MINUS) {
124+
while (_current_token._type == MUL || _current_token._type == DIV) {
120125
auto token = _current_token;
121-
if (token._type == PLUS) {
122-
eatToken(PLUS);
123-
result += getTerm();
124-
} else if (token._type == MINUS) {
125-
eatToken(MINUS);
126-
result -= getTerm();
126+
if (token._type == MUL) {
127+
eatToken(MUL);
128+
result *= getTerm();
129+
} else if (token._type == DIV) {
130+
eatToken(DIV);
131+
result /= getTerm();
127132
}
128133
}
129134
return result;

0 commit comments

Comments
 (0)