RPN计算器(将操作数应用到堆栈时出现问题)
RPN Calculator (issues with applying operands to the stack)
我目前正在为一个类构建RPN计算器,该类必须通过int堆栈和各种函数来运行。它还必须通过cin语句获取输入,然后将其排序为整数或操作数,并将其推送到堆栈上或从类中启动适当的函数进行计算。
大部分我都已经想好了,而且还在工作,然而我有一个非常奇怪的问题,我无法解决。
它会对我的第一组数字和第一个操作数进行微调(例如,我输入1 2 3,堆栈将显示3、2、1作为内容),但在我应用第二个操作数后,我会在每个答案之前放入零。
示例:
输入:1 2+2*
预期输出:6
我得到的:0,2,0,3
我不确定这是堆栈的push()函数中的错误,还是main中的错误或其他错误。我一直找不到它。任何帮助都将不胜感激,哪怕只是指向正确方向的一点!
以下是我认为导致问题的代码部分:
主要功能:
int main(){
Stack mystack;
std::string getIt; // taken as input
int pushIt; // converted to int and pushed if nessecary
do{
// get user input
std::cin >> getIt;
if(getIt == "@"){};
if(getIt == "!") mystack.negate();
if(getIt == "+") mystack.add();
if(getIt == "-") mystack.subt();
if(getIt == "/") mystack.div();
if(getIt == "%") mystack.mod();
if(getIt == "SUM") mystack.sumof();
if(getIt == "R") mystack.reverse();
if(getIt == "#") mystack.print();
if(getIt == "$") mystack.clear();
else {
pushIt = atoi(getIt.c_str()); // I have no idea if this was
//utilized correctly, feel free
mystack.push(pushIt); // to correct me here if not..
}
}
while(getIt!="@"); // breaks on @
return 0;
}
推送、弹出和顶部操作员:
void Stack::push(const int& val){
Node* newNode = new Node;
newNode->data = val;
if(!head){
head = newNode;
return;
}
newNode->next = head;
head = newNode;
}
void Stack::pop(){
if(!head)
return;
if(head->next == NULL){
delete head;
head = NULL;
return;
}
Node* deleteIt = head;
head = head->next;
delete deleteIt;
return;
}
const int& Stack::top() const throw(Oops) { //Oops returns
if(head == NULL){ // an error variable
std::cout<<"ERROR!! : No values in the stack.";
}
return head->data;
}
// I also don't know if I used the throw right here..
万一我真的做错了什么。。。这是我的一个操作函数(+),其他的都是类似的编码。
void Stack::add(){
int num1 = top();
pop();
int num2 = top();
pop();
int sum = num2+num1;
push(sum);
return;
}
谢谢!
您的流控制不正确。考虑当用户输入+
:时会发生什么
if(getIt == "+") mystack.add(); // <== this happens
if(getIt == "-") mystack.subt(); // nope
if(getIt == "/") mystack.div(); // nope
// ... snip ...
if(getIt == "$") mystack.clear(); // nope
else { // this else is associated ONLY with the
// previous if. As a result...
pushIt = atoi(getIt.c_str()); // <== this happens too!
mystack.push(pushIt);
}
将+
处理为加法操作数和数字和atoi("+") == 0
。问题是,你所有的if
都是独立的,它们不应该是:
if (getIt == "+") ...
else if (getIt == "-") ...
else if (getIt == "/") ...
...
else {
// handle int here
}
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 堆栈问题(平衡表达式问题集)
- 使用指针计算堆栈问题的大 O 表示法
- 使用泛型类型推送到堆栈时出现问题
- 我的堆栈和库存清单程序的结构有什么问题?
- C++ - 面试问题中的堆栈上的对象
- 在我自己的堆栈中实现top的问题
- 创建堆栈时出现问题!(街机游戏)
- 我遇到了有关递归的堆栈问题
- 关于 std::堆栈推送的分段错误的问题
- C++堆栈内存管理问题
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
- 数组问题:变量周围的堆栈'arr'已损坏
- 关于在C 中实现堆栈的问题
- 未定义对调用堆栈库的引用出现问题
- 我的堆栈中的弹出方法有什么问题?
- 调试堆栈损坏问题
- 我的矩阵堆栈实现(OpenGL ES 2.0)有什么问题
- 无锁的堆栈:在POP()期间检查危险指针时可见性问题