Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 表达式树给出错误答案_C++_Expression Trees - Fatal编程技术网

C++ 表达式树给出错误答案

C++ 表达式树给出错误答案,c++,expression-trees,C++,Expression Trees,编辑 这是家庭作业,所以请不要直接编码。只是提示一下,谢谢 我正在从事一个项目,该项目将使用表达式树来派生各种内容,然后对它们执行操作。现在我不太担心派生部分,我只想把操作部分写下来 我使用的表达式树代码适用于整数,但一旦我输入“x”或任何其他变量,我的答案就错了。我的程序使用后缀表达式字符串。。。下面是一个正确和错误的例子 5 6+返回11。正确的 5x6x+返回11。不正确的需要是11倍 这是我的密码: // This is the expression tree code I'm usin

编辑

这是家庭作业,所以请不要直接编码。只是提示一下,谢谢

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

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

5 6+返回11。正确的

5x6x+返回11。不正确的需要是11倍

这是我的密码:

// 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';
}
//这是我正在使用的表达式树代码
#ifndef EXPRNODE_H
#定义EXPRNODE_H
#包含//表示空
使用名称空间std;
//=======================================================类扩展节点
类扩展节点{
公众:
ExprNode(字符操作,ExprNode*左,ExprNode*右);
ExprNode(int-val);
int eval()const;//计算表达式树。返回结果。
私人:
char _op;//一个+,-,*,/#
int _value;//用于常量的整数值。
ExprNode*_left;//左子树
ExprNode*_right;//右子树
};
#恩迪夫
//===============================================================================扩展节点构造函数
//为二进制运算符构造节点。
ExprNode::ExprNode(字符操作,ExprNode*左,ExprNode*右){
_op=操作;
_左=左;
_右=右;
}
//==================================================================================扩展节点构造函数
//为整型常量构造一个节点
ExprNode::ExprNode(intv){
_op='#';
_值=v;
_左=空;
_右=空;
}
//============================================================================ExprNode::eval
int ExprNode::eval()常量{
//递归计算表达式树并返回结果。
int结果;
开关(_op){
格“+”:
结果=_left->eval()+_right->eval();
打破
案例'-':
结果=_left->eval()-_right->eval();
打破
案例“*”:
结果=_left->eval()*_right->eval();
打破
案例“/”:
结果=_left->eval()/_right->eval();
打破
案例“#”:
result=\u value;//一个整型常量
打破
}
返回结果;
}
布尔等运算符(字符操作数)
{
返回操作数=='+'| |操作数=='-'| |操作数=='*'| |操作数=='/'| |操作数=='^';
}
布尔isNumber(字符电位编号)
{

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

哦,是的……对不起,我忘了提到我不想要直截了当的答案,因为这是家庭作业……谢谢你没有这么做。我在想,也许可以在我的表达式树方法中将x与数字分开,稍后再放回去。我觉得你的方法可能更好,但我必须考虑一下。那就是nks阿加尼认为这些建议已经足够了。你们应该将其标记为答案并投票表决。
// 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;
}