Created
September 11, 2023 21:51
-
-
Save xsa-dev/98d0f74323ce0b23ceb22739e8e80f8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stack> | |
#include <string> | |
#include <sstream> | |
#include <cmath> | |
using namespace std; | |
bool isOperator(const string& token) { | |
return token == "+" || token == "-" || token == "*" || token == "/"; | |
} | |
double performOperation(double operand1, double operand2, const string& op) { | |
if (op == "+") | |
return operand1 + operand2; | |
else if (op == "-") | |
return operand1 - operand2; | |
else if (op == "*") | |
return operand1 * operand2; | |
else if (op == "/") { | |
if (operand2 == 0) { | |
cerr << "Ошибка: деление на ноль!" << endl; | |
exit(1); | |
} | |
return operand1 / operand2; | |
} | |
return 0.0; | |
} | |
double evaluateRPN(const string& rpnExpression) { | |
stack<double> operands; | |
stringstream ss(rpnExpression); | |
string token; | |
while (ss >> token) { | |
if (!isOperator(token)) { | |
double operand; | |
if (istringstream(token) >> operand) { | |
operands.push(operand); | |
} else { | |
cerr << "Ошибка: недопустимый токен - " << token << endl; | |
exit(1); | |
} | |
} else { | |
if (operands.size() < 2) { | |
cerr << "Ошибка: недостаточно операндов для оператора - " << token << endl; | |
exit(1); | |
} | |
double operand2 = operands.top(); | |
operands.pop(); | |
double operand1 = operands.top(); | |
operands.pop(); | |
double result = performOperation(operand1, operand2, token); | |
operands.push(result); | |
} | |
} | |
if (operands.size() != 1) { | |
cerr << "Ошибка: недопустимое количество операндов и операторов!" << endl; | |
exit(1); | |
} | |
return operands.top(); | |
} | |
int main() { | |
cout << "Введите выражение в обратной польской записи: "; | |
string rpnExpression; | |
getline(cin, rpnExpression); | |
double result = evaluateRPN(rpnExpression); | |
cout << "Результат: " << result << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment