我目前正致力於在RPN計算器上構建一個類,該類必須通過一系列整數和各種函數來運行。它還必須通過cin語句獲得輸入,然後將其分類爲整數或操作數,然後將其推入堆棧或從類中啓動適當的函數進行計算。RPN計算器(將操作數應用於堆棧的問題)
大部分我已經想通了,但我有一個很奇怪的問題,我不明白。
這將採取我的第一組數字和第一操作數罰款(例如,我輸入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;
}
PUSH,POP,和頂級運營商:
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..
而且,只是incase我實際上做錯了這裏,而不是...這是我的一個操作功能(+),其他人都編碼類似。
void Stack::add(){
int num1 = top();
pop();
int num2 = top();
pop();
int sum = num2+num1;
push(sum);
return;
}
謝謝!