diff --git a/README.md b/README.md index 152f96e..2855930 100644 --- a/README.md +++ b/README.md @@ -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 ``` @@ -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`等指令。 diff --git a/src/expression_calc.cpp b/src/expression_calc.cpp index 6c2be48..46e4086 100644 --- a/src/expression_calc.cpp +++ b/src/expression_calc.cpp @@ -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() { diff --git a/test.sh b/test.sh index 92aadbd..7ff7091 100755 --- a/test.sh +++ b/test.sh @@ -7,9 +7,9 @@ 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 @@ -17,3 +17,5 @@ hello() 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