给出错误答案的表达式树

发布于 2024-11-02 17:26:09 字数 4970 浏览 1 评论 0原文

编辑

这是家庭作业,因此请不要直接使用代码。只是提示,谢谢!

我正在开发一个项目,该项目将使用表达式树来派生各种事物,然后对它们执行操作。现在我不太担心推导部分,我只想把操作部分搞下来。

我使用的表达式树代码适用于整数,但是一旦我输入“x”或任何其他变量,我的答案就是错误的。我的程序使用后缀表达式字符串...下面是正确和错误的示例。

5 6 + 返回 11。正确

5x 6x + 返回 11。不正确需要是 11x

这是我的代码:

// This is the expression tree code I'm using
#ifndef EXPRNODE_H
#define EXPRNODE_H

#include <cstdlib>  // for NULL
using namespace std;

//====================================== class ExprNode
class ExprNode {
 public:
    ExprNode(char oper, ExprNode* left, ExprNode* right);
    ExprNode(int val);
    int eval() const; // Evaluate expr tree. Return result.

 private:
    char      _op;    // one of +, -, *, /, #
    int       _value; // integer value used for constants.
    ExprNode* _left;  // left subtree
    ExprNode* _right; // right subtree
};
#endif

//============================================= ExprNode constructor
// Constructs node for a binary operator.
ExprNode::ExprNode(char oper, ExprNode* left, ExprNode* right) {
    _op    = oper;
    _left  = left;
    _right = right;
}

//============================================== ExprNode constructor
// Constructs a node for an integer constant
ExprNode::ExprNode(int v) {
    _op    = '#';
    _value = v;
    _left  = NULL;
    _right = NULL;
}

//===================================================== ExprNode::eval
int ExprNode::eval() const {
    // Recursively evaluate expression tree and return result.
    int result;
    switch (_op) {
        case '+': 
                result = _left->eval() + _right->eval();
                break;
        case '-': 
                result = _left->eval() - _right->eval();
                break;
        case '*':
                result = _left->eval() * _right->eval();
                break;
        case '/':
                result = _left->eval() / _right->eval();
                break;
        case '#': 
                result = _value;  // an integer constant
                break;
     }
     return result;
}

bool isOperator (char operand)
{
    return operand == '+' || operand == '-' || operand == '*' || operand == '/' || operand == '^';
}

bool isNumber (char potentialNumber)
{
    return potentialNumber >= '0' && potentialNumber <= '9';
}

bool isX (char letter)
{
    return letter == 'x' || letter == 'X';
}

我不会包含从中缀到后缀的代码,因为它是不必要的(我认为).... 接下来是表达式树和计算的代码

// the expression string is the postfix expression I returned previously
void expressionTree(string expression)
{
    string tempNum = "";
    string tempNum2 = "";
    int count = 1;
    int tempNumInt;
    int tempNum2Int;

    // creates a blank total value and blank numbers
    ExprNode* totalVal = new ExprNode('+', new ExprNode(0), new ExprNode(0));
    ExprNode* tNum;
    ExprNode* tNum2;

    // loop through the postfix expression
    for (unsigned int iterator = 0; iterator < expression.length(); iterator++)
    {
        if (isOperator(expression[iterator]))
        {
                    // Don't need to worry about at the moment
            if (expression[iterator] == '^')
            {
                // go to derivative later
            }
            else
            {
                if (count % 2 != 0)
                {
                    // we'll do different derivatives here.... for now just add, subtract, multiply, divide
                    totalVal = new ExprNode(expression[iterator], tNum, tNum2);
                }
                else if (count % 2 == 0 && expression[iterator] == '+' || expression[iterator] == '*')
                {
                    totalVal = new ExprNode(expression[iterator], tNum, totalVal);
                }
                else if (count % 2 == 0 && expression[iterator] == '-' || expression[iterator] == '/')
                {
                    totalVal = new ExprNode(expression[iterator], totalVal, tNum);
                }
            }
            count++;
        }
        if (isNumber(expression[iterator]) && count % 2 != 0)
        {
            tempNum += expression[iterator];
        }
        else if (isNumber(expression[iterator]) && count % 2 == 0)
        {
            tempNum2 += expression[iterator];
        }
        if (expression[iterator] == ' ' && count % 2 != 0)
        {
            tempNumInt = atoi (tempNum.c_str());
            tNum = new ExprNode(tempNumInt);
            tempNum = "";
            count++;
        }
        else if (expression[iterator] == ' ' && count % 2 == 0)
        {
            tempNum2Int = atoi (tempNum2.c_str());
            tNum2 = new ExprNode(tempNum2Int);
            tempNum2 = "";
            count++;
        }
        else if (expression[iterator] == ' ')
        {
            count++;
        }
    }
    cout << totalVal->eval() << endl;
}

我将尝试解释任何不清楚的内容。提前致谢。

EDIT

This is homework so no straight up code please. Just hints, thank you!

I'm working on a project that will use an expression tree to derive a variety of things and then perform operations on them. Right now I'm not too worried about the deriving part, I just want to get the operations part down.

The expression tree code that I'm using works for integers but once I input "x" or any other variable my answer is wrong. My program works with postfix expression strings... below is an example of what is right and wrong.

5 6 + returns 11. correct

5x 6x + returns 11. incorrect needs to be 11x

Here is my code:

// This is the expression tree code I'm using
#ifndef EXPRNODE_H
#define EXPRNODE_H

#include <cstdlib>  // for NULL
using namespace std;

//====================================== class ExprNode
class ExprNode {
 public:
    ExprNode(char oper, ExprNode* left, ExprNode* right);
    ExprNode(int val);
    int eval() const; // Evaluate expr tree. Return result.

 private:
    char      _op;    // one of +, -, *, /, #
    int       _value; // integer value used for constants.
    ExprNode* _left;  // left subtree
    ExprNode* _right; // right subtree
};
#endif

//============================================= ExprNode constructor
// Constructs node for a binary operator.
ExprNode::ExprNode(char oper, ExprNode* left, ExprNode* right) {
    _op    = oper;
    _left  = left;
    _right = right;
}

//============================================== ExprNode constructor
// Constructs a node for an integer constant
ExprNode::ExprNode(int v) {
    _op    = '#';
    _value = v;
    _left  = NULL;
    _right = NULL;
}

//===================================================== ExprNode::eval
int ExprNode::eval() const {
    // Recursively evaluate expression tree and return result.
    int result;
    switch (_op) {
        case '+': 
                result = _left->eval() + _right->eval();
                break;
        case '-': 
                result = _left->eval() - _right->eval();
                break;
        case '*':
                result = _left->eval() * _right->eval();
                break;
        case '/':
                result = _left->eval() / _right->eval();
                break;
        case '#': 
                result = _value;  // an integer constant
                break;
     }
     return result;
}

bool isOperator (char operand)
{
    return operand == '+' || operand == '-' || operand == '*' || operand == '/' || operand == '^';
}

bool isNumber (char potentialNumber)
{
    return potentialNumber >= '0' && potentialNumber <= '9';
}

bool isX (char letter)
{
    return letter == 'x' || letter == 'X';
}

I'm not going to include the code going from infix to postfix because it is unnecessary (I think).... next is the code for the expression tree and calculations

// the expression string is the postfix expression I returned previously
void expressionTree(string expression)
{
    string tempNum = "";
    string tempNum2 = "";
    int count = 1;
    int tempNumInt;
    int tempNum2Int;

    // creates a blank total value and blank numbers
    ExprNode* totalVal = new ExprNode('+', new ExprNode(0), new ExprNode(0));
    ExprNode* tNum;
    ExprNode* tNum2;

    // loop through the postfix expression
    for (unsigned int iterator = 0; iterator < expression.length(); iterator++)
    {
        if (isOperator(expression[iterator]))
        {
                    // Don't need to worry about at the moment
            if (expression[iterator] == '^')
            {
                // go to derivative later
            }
            else
            {
                if (count % 2 != 0)
                {
                    // we'll do different derivatives here.... for now just add, subtract, multiply, divide
                    totalVal = new ExprNode(expression[iterator], tNum, tNum2);
                }
                else if (count % 2 == 0 && expression[iterator] == '+' || expression[iterator] == '*')
                {
                    totalVal = new ExprNode(expression[iterator], tNum, totalVal);
                }
                else if (count % 2 == 0 && expression[iterator] == '-' || expression[iterator] == '/')
                {
                    totalVal = new ExprNode(expression[iterator], totalVal, tNum);
                }
            }
            count++;
        }
        if (isNumber(expression[iterator]) && count % 2 != 0)
        {
            tempNum += expression[iterator];
        }
        else if (isNumber(expression[iterator]) && count % 2 == 0)
        {
            tempNum2 += expression[iterator];
        }
        if (expression[iterator] == ' ' && count % 2 != 0)
        {
            tempNumInt = atoi (tempNum.c_str());
            tNum = new ExprNode(tempNumInt);
            tempNum = "";
            count++;
        }
        else if (expression[iterator] == ' ' && count % 2 == 0)
        {
            tempNum2Int = atoi (tempNum2.c_str());
            tNum2 = new ExprNode(tempNum2Int);
            tempNum2 = "";
            count++;
        }
        else if (expression[iterator] == ' ')
        {
            count++;
        }
    }
    cout << totalVal->eval() << endl;
}

I'll try to explain anything that is unclear. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许你一世情深 2024-11-09 17:26:09

我并不是指出确切的错误,而是给你一个建议:int ExprNode::eval() const 不应该返回 'int'。这不足以处理变量结果,例如“11x”(这不能用简单的 int 表示)。您必须创建自己的结构来存储结果的整数部分和变量部分(最后一个是可选的)。

I'm not pointing out the exact mistake, but giving you an advice: int ExprNode::eval() const should not return 'int'. That's not enough to handle the variable results, like "11x" (this cannot be represented with a simple int). You'll have to create your own structure that stores the integer part and the variable part of the result (with this last one being optional).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文