gpt4 book ai didi

c++ - -1 #IND 问题

转载 作者:太空狗 更新时间:2023-10-29 20:47:31 30 4
gpt4 key购买 nike

我目前正在为二叉树编写 C++。整件事都写好了,但是,无论我想评估什么表达式,我都会让命令提示符告诉我 -1.#IND。关于解决此问题的任何想法,甚至这意味着什么?

提前致谢

代码:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
template<typename T> struct TreeNode
{
TreeNode(const T& value, TreeNode<T>* left = NULL, TreeNode<T>* right = NULL)
{
Value = value;
Left = left;
Right = right;
}

T Value;
TreeNode<T>* Left;
TreeNode<T>* Right;

bool IsLeaf() const
{
return Left == NULL && Right == NULL;
}
};


double ValueOf(TreeNode<char>* treeNode)
{


if ( treeNode->IsLeaf() )
{
return treeNode->Value - '0';
}
else
{
switch(treeNode->Value)
{
case '+':
return ValueOf(treeNode->Left) + ValueOf(treeNode->Right);
break;

case '-':
return ValueOf(treeNode->Left) - ValueOf(treeNode->Right);
break;

case '*':
return ValueOf(treeNode->Left) * ValueOf(treeNode->Right);
break;

case '/':
return ValueOf(treeNode->Left) / ValueOf(treeNode->Right);
break;
}


}
}



void main()
{
string expression;

cout << "Please enter an expression: ";

cin >> expression;


TreeNode<char> *newLeaf;
TreeNode<char> *treeRoot;
TreeNode<char> *currentNode;
TreeNode<char> *newRoot;
TreeNode<char> *newChild;


treeRoot = NULL;
currentNode = treeRoot;


for (int i = 0; i < expression.length(); i++)
{

if ( (expression[i] >= 0 ) || ( expression[i] <= 9 ) )
{

newLeaf = new TreeNode <char> (expression[i]);


if ( currentNode == NULL)
{
treeRoot = currentNode = newLeaf;
}
else
{
currentNode->Right = newLeaf;
}
}

else if ( (( expression[i] == '+' || expression[i] == '-') || (expression[i] == '*' || expression[i] == '/' )) && currentNode->Right == NULL )
{
newRoot = new TreeNode <char> (expression[i]);
newRoot->Left = treeRoot;
treeRoot = newRoot;
currentNode = newRoot;
}

else if (expression[i] == '*' || expression[i] == '/')
{
newChild = new TreeNode <char> (expression[i]);
newChild->Left = currentNode->Right;
currentNode->Right = newChild;
currentNode = newChild;
}
}

double result = ValueOf(treeRoot);
cout << "The result is: " << result << endl;
system("pause");
}

最佳答案

这意味着您对 doublefloat 做了一些非法的事情(比如取负数的平方)。另见此处:http://www.johndcook.com/IEEE_exceptions_in_cpp.html

关于c++ - -1 #IND 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412768/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com