我正在嘗試爲RPN計算器編寫代碼,我正在努力使它正確計算多個「左」和「右」操作數。C++的RPN計算器
到目前爲止,我的代碼工作的投入,如: 10 15 + = 25
我無法搞清楚如何獲得這些輸入正確輸出:
輸入:100 10 50 25/* - -2/=輸出:-40
此外,現在我只是將堆棧大小除以2,它適用於某些錯誤檢查,但然後它打印錯誤的類似上/下輸入。 100 10 50 25/* - -2/= -40
我該如何獲得代碼來檢查下面這兩個輸入的錯誤?
輸入:10 20 */=輸出:錯誤:有太多的運營商
12 20 30/= Error: Too many operand
任何幫助將不勝感激,謝謝!
#include <iostream>
#include <stack>
#include <string>
#include <sstream> //make use of a class called istringstream
#include<iomanip>
using namespace std;
//Function prototype for isOperator
bool isOperator(const string& input);
//Function prototype for perforOperation
int performOperation(const string& input, stack<double>& calcStack);
int main()
{
cout << "RPN Calculator: " << endl;
cout << "Input\n";
stack<double> calcStack;
string input;
while(input != "0")
{
//Terminate program when 0 is entered by user
while(input != "=")
{
// get input
cin >> input;
// check for being numeric value
double num;
if(istringstream(input) >> num)
{
//use push function
calcStack.push(num);
}
// check for operator
else if(isOperator(input))
{
performOperation(input, calcStack);
}
// If user enters 0 on a line followed by a new line, the program exits ????????????
else if(input == "0\n")
{
return -1;
}
// invalid output check
//else
//{
//cout << "Invalid input" << endl;
//}
}
}
}
bool isOperator(const string& input)
{
string operators[] = {"-", "+", "*", "/"};
for(int i=0; i<4; i++)
{
if(input == operators[i])
{
return true;
}
}
return false;
}
int performOperation(const string& input, stack<double>& calcStack)
{
double firstOperand;
double secondOperand;
double result;
if(calcStack.size() > 2) //Error check gives a false error for last input ???
{
cout << "Error: too many operands" << endl;
return 1;
}
//Error chceck for too many operators ////STILL PRINT OUTPUT???
if(calcStack.size() < 2)
{
cout << "Error: too many operators" << endl;
return 1;
}
secondOperand = calcStack.top();
calcStack.pop();
firstOperand = calcStack.top();
calcStack.pop();
if(input == "-")
{
result = firstOperand-secondOperand;
}
else if (input == "+")
{
result = firstOperand + secondOperand;
}
else if (input == "*")
{
result = firstOperand * secondOperand;
}
else if(input == "/")
{
result = firstOperand/secondOperand;
}
// If user enters 0 on a line followed by a new line, the program exits ???????????
else if(input == "0\n")
{
return -1;
}
//Division by zero error
if(secondOperand == 0)
{
cout << "Error: Division by 0.\n";
return -1;
}
cout << "Output\n";
cout << result << endl;
calcStack.push(result);
return 0;
}
這是調試器的工作,man!當前的問題是'if(calcStack.size()> 2)'它會是什麼。所有操作員完成後,如果有多個操作數,則最後只有很多操作數。 – user4581301
調整:isOperator可以簡化爲搜索字符串中的字符。 'static const string operators =「 - + * /」; if(input.length()== 1)返回operators.find_first_of(input [0])!= string :: npos;返回false;' – user4581301
你可以研究其他人完成這項任務。爲「C++ rpn計算器」搜索StackOverflow。 –