Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Result: 7.000000
```

```shell
sin(PI()/2)*6-tan(atan(6))
sin(PI/2)*6-tan(atan(6))

Result: -0.000000
```
Expand All @@ -49,6 +49,12 @@ fuck(6)+7
[Function Not Found]: fuck.
```

```shell
-10-(2*(-PI))+E

Result: -0.998533
```

### 在`example/xCalc.cpp`中

使用`addFunc`接口添加`if`、`fib`、`hello`等指令。
Expand Down
39 changes: 38 additions & 1 deletion src/expression_calc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,44 @@ double eXpressionCalc::evalNotation(const Notation_t& notation) {
}

void eXpressionCalc::setExpression(Expression_t expression) {
Expr = std::move(expression);
std::string modified_expr = expression;

// 1. If the first character is '-', prepend '0' for negative number
if (!modified_expr.empty() && modified_expr[0] == '-') {
modified_expr = "0" + modified_expr; // Change "-2" to "0-2"
}

// 2. Replace all "(-" with "(0-" to handle negative numbers in parentheses
size_t pos = 0;
while ((pos = modified_expr.find("(-", pos)) != std::string::npos) {
modified_expr.replace(pos, 2, "(0-");
pos += 3; // Skip past "(0-"
}

// 3. Append "()" to "PI" if not followed by '('
pos = 0;
while ((pos = modified_expr.find("PI", pos)) != std::string::npos) {
if (pos + 2 >= modified_expr.size() || modified_expr[pos + 2] != '(') {
modified_expr.insert(pos + 2, "()");
pos += 4; // Skip over "PI()"
} else {
pos += 3; // Skip over "PI("
}
}

// 4. Append "()" to "E" if not followed by '('
pos = 0;
while ((pos = modified_expr.find("E", pos)) != std::string::npos) {
if (pos + 1 >= modified_expr.size() || modified_expr[pos + 1] != '(') {
modified_expr.insert(pos + 1, "()");
pos += 3; // Skip over "E()"
} else {
pos += 2; // Skip over "E("
}
}

// 5. Assign the processed expression to internal member
Expr = std::move(modified_expr);
}

const Error_t& eXpressionCalc::getError() {
Expand Down
8 changes: 5 additions & 3 deletions test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ popd
calc_bin=./build/xCalc

echo '
if(sin(20)
(cos(20) + PI())
(sin(PI()) - 20)
if(sin(-20)
(cos(20) + PI)
(sin(-PI) - 20)
) + 30;
hello()
' | $calc_bin

for i in {1..100}; do
echo "fib(1, 1, $i) / fib(1, 1, $i - 1)" | $calc_bin
done

echo '-10-(2*(-PI))+E' | $calc_bin