RPN计算器(将操作数应用到堆栈时出现问题)

RPN Calculator (issues with applying operands to the stack)

本文关键字:问题 堆栈 计算器 操作数 应用 RPN      更新时间:2023-10-16

我目前正在为一个类构建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
}