Skip to content

Support for negative numbers, PI and E can be used directly.#7

Open
foamzzz wants to merge 1 commit intoW-Mai:masterfrom
foamzzz:negative
Open

Support for negative numbers, PI and E can be used directly.#7
foamzzz wants to merge 1 commit intoW-Mai:masterfrom
foamzzz:negative

Conversation

@foamzzz
Copy link

@foamzzz foamzzz commented May 8, 2025

The original function in expression_calc.cpp is as follows:

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

The expression obtained from the original function has been processed to support calculations involving negative numbers, such as -10-(2*(-PI))+E, Result: -0.998533. Additionally, PI and E no longer require manually added parentheses, making the process more intelligent.

void eXpressionCalc::setExpression(Expression_t 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);
}

The test.sh and readme.md have been updated with examples and a few minor modifications.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant