【发布时间】:2013-10-18 22:52:08
【问题描述】:
讨厌几天前在同一程序上获得帮助后回来寻求帮助,但我真的很难完成这个程序。简而言之,我需要创建一个带有链表堆栈的后缀符号计算器 (RPN),它允许我执行诸如 5 5 5 + + (=15) 之类的表达式。我现在已经设法完成了主要的计算部分,但我正在努力处理两个错误。其中之一是“操作符过多”,另一个是“操作数过多”。目前正在研究“太多操作员”,我觉得我很接近但不能完全到达那里。
如果用户在第一个条目中输入 5 5 ++,它会捕捉到它并说“操作数太多”。但是,如果之前计算的堆栈中已经有东西,然后他们键入相同的表达式 5 5 ++,这并不是说堆栈是空的,而是输出一个使用先前数字的答案。如果有人能看到我在这里出错的地方,并指出我找出另一个错误“太多运算符”(例如:5 5 5 +)的方向,那将不胜感激。再次提前感谢。
(在搞砸了更多之后,似乎我做的计算越多,实际上需要放置的运算符就越多才能被认为是空的。我猜我需要在每个表达式之前的某个地方 popVal 但不确定在哪里说吧,因为我已经尝试了很多地方,但它不起作用)
#include<iomanip>
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
class SLLNode
{
double data;
SLLNode *top;
SLLNode *ptr;
public:
SLLNode()
{
top = NULL;
ptr = NULL;
}
bool isEmpty()
{
return top == 0;
}
void pushVal(double val)
{
SLLNode *next = new SLLNode;
next -> data = val;
next -> ptr = top;
top = next;
}
double popVal()
{
if (isEmpty())
{
cout << "Error: Too many operators" << endl;
}
else
{
SLLNode *next = top -> ptr;
double ret = top -> data;
delete top;
top = next;
return ret;
}
}
void print()
{
cout << top -> data << endl;
}
};
bool isOperator(const string& input)
{
string ops[] = {"+", "-", "*", "/"};
for(int i = 0; i < 4; i++)
{
if(input == ops[i])
{
return true;
}
}
return false;
}
void performOp(const string& input, SLLNode& stack)
{
double fVal, sVal;
int errorCheck = 0;
sVal = stack.popVal();
fVal = stack.popVal();
if(input == "+")
{
stack.pushVal(fVal + sVal);
}
else if(input == "-")
{
stack.pushVal(fVal - sVal);
}
else if(input == "*")
{
stack.pushVal(fVal * sVal);
}
else if(input == "/" && sVal != 0)
{
stack.pushVal(fVal / sVal);
}
if(input == "/" && sVal == 0)
{
cout << "Error: Division by zero" << endl;
errorCheck = 1;
}
if(errorCheck == 0)
{
stack.print();
}
}
int main()
{
cout << "::::::::::::::::RPN CALCULATOR:::::::::::::::::" << endl;
cout << "::TYPE IN A POSTFIX EXPRESSION OR 'q' TO QUIT::" << endl;
cout << ":::::::::::::::::::::::::::::::::::::::::::::::" << endl << endl;
string input;
SLLNode stack;
while(true)
{
cin >> input;
double num;
if(istringstream(input) >> num)
{
stack.pushVal(num);
}
else if (isOperator(input))
{
performOp(input, stack);
}
else if (input == "q")
{
return 0;
}
}
}
【问题讨论】:
-
"如果之前计算的堆栈中已经有东西,然后他们输入相同的表达式
5 5 + +,这并不是说堆栈是空的,而是输出一个答案以前的号码正在使用。”为什么这是个问题?如果您输入2,然后输入5 5 + +,您不想打印12吗? -
与
5 5 5 +类似:为什么会出现这个问题?如果我最终想输入5 5 5 + +怎么办 - 为什么要阻止我这样做? -
我只希望每一行都是它自己的表达方式。如果有人输入表达式 5 5 5 +,它必须输出“太多运算符”。抱歉,不完全确定你们在问什么,因为我对此有点陌生。它应该只准备 (x) 数量的运算符和 (x-1) 数量的操作数,如果不是这种情况,那么我需要打印一个错误。如果有人只输入 2,然后按 Enter,然后输入 5 5 ++,我仍然希望它说操作数太多。如果有人输入 2,请输入,然后输入 5 5 +,我希望它输入 10。谢谢。
标签: c++ linked-list stack postfix-notation rpn