我目前正在为二叉树编写一个 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");
}
最佳答案
这意味着你对 double
或 float
做了一些非法的事情(比如取负数的 sqrt)。另见此处:http://www.johndcook.com/IEEE_exceptions_in_cpp.html
关于c++ - -1 #IND 问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5412768/