正在计算表达式C++
Evaluating expression C++
我在使用这个没有指针作为参数的求值函数时遇到了一些问题。
以下是类定义:
class ExpressionTree
{
private:
double data; // Used for leaf nodes only.
char operation; // Used for non-leaf nodes only.
ExpressionTree *left; // Will be NULL for a leaf.
ExpressionTree *right; // Will be NULL for a leaf.
};
正如您所看到的,表达式树中只有left
和right
子树的指针。
以下是我对evaluate()
函数的尝试(注意没有指针作为参数传递)
double ExpressionTree::evaluate() const {
if(left != NULL && right != NULL) {
double val;
double left_val = left->data;
double right_val = right->data;
if(operation == '+') val = left->evaluate() + right->evaluate();
else if(operation == '*') val = left->evaluate() + right->evaluate();
else val = this->data;
return val;
}
else {
return data;
}
}
当对这个代码运行它时,我会得到一个分段错误:
ExpressionTree buildComplex() {
double x, y, z;
cout << "enter three double values, x, then y, then zn";
cin >> x >> y >> z;
ExpressionTree ex(x), ey(y), ez(z), e2(2),
yz = ey * ez,
y2 = e2 * ey,
sum1 = ex + yz,
full = sum1 + y2;
return full;
}
void test4() {
cout << "test4: construct and evaluate more complexn";
ExpressionTree e = buildComplex();
cout << "x + y * z + 2 * y = " << e.evaluate() << endl;
}
我认为分段错误来自evaluate()
函数中的递归调用。
我要问的问题是:在没有节点作为参数传递给函数的情况下,如何递归地评估树?如果根节点下面只有一层,我可以理解,但会有多个层,我不知道如何解决所有其他层。
谢谢!
您在同一个节点上调用evaluate
,创建一个无限循环。
如果要在子表达式上调用它,请使用left->evaluate()
。
可能还有更多的问题,我注意到的是这个问题:
else if(right != NULL)
这毫无意义,仅仅因为left
不是NULL
,你就要忽略正确的子表达式吗?
您的evaluate()
方法是无稽之谈。它应该看起来像这样:
double ExpressionTree::evaluate() const
{
if (left != NULL && right != NULL)
{
switch (operation)
{
case '+':
return left->evaluate()+right->evaluate();
case '-':
// remaining operators left as an exercise for the reader
// ....
}
}
// I'm assuming there are only binary operators,
// but if you have unary operators, i.e. unary '-', it's a simple
// extension of what's here
return data;
}
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 提升精神:解析布尔表达式并简化为规范范式
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用正则表达式regex_search在字符串中查找字符串
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 概念中的cv限定符需要表达式参数列表
- 为什么constexpr的性能比正常表达式差
- 对于结构,表达式必须是可修改的ivalue
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 将fold表达式与std::一起用于两个元组
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 标记 '","' 之前的预期主表达式
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 带有用户定义类的c++折叠表达式
- 即使使用调试编译标志,表达式也是"optimized out"
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 这 4 个 lambda 表达式之间有什么区别?