Приведенный выше код может быть организован в заголовочный файл Calculator.h и файл реализации Calculator.cpp.
Calculator.h:
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include <string>
class Calculator {
private:
int getPriority(char op);
std::string convertToRPN(std::string infixExp);
double evaluateRPN(std::string postfixExp);
public:
std::string infixToPrefix(std::string infixExp);
std::string infixToPostfix(std::string infixExp);
double calculateExpression(std::string infixExp);
};
#endif
Calculator.cpp:
#include "Calculator.h"
#include <stack>
#include <cmath>
int Calculator::getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else if (op == '^') {
return 3;
}
return 0;
}
std::string Calculator::convertToRPN(std::string infixExp) {
std::stack<char> opStack;
std::string postfixExp;
for (int i = 0; i < infixExp.length(); i++) {
char c = infixExp[i];
if (isalnum(c)) {
postfixExp += c;
} else if (c == '(') {
opStack.push('(');
} else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfixExp += opStack.top();
opStack.pop();
}
opStack.pop();
} else {
while (!opStack.empty() && getPriority(c) <= getPriority(opStack.top())) {
postfixExp += opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
while (!opStack.empty()) {
postfixExp += opStack.top();
opStack.pop();
}
return postfixExp;
}
double Calculator::evaluateRPN(std::string postfixExp) {
std::stack<double> numStack;
for (int i = 0; i < postfixExp.length(); i++) {
char c = postfixExp[i];
if (isdigit(c)) {
numStack.push(c - '0');
} else {
double num2 = numStack.top();
numStack.pop();
double num1 = numStack.top();
numStack.pop();
switch(c) {
case '+':
numStack.push(num1 + num2);
break;
case '-':
numStack.push(num1 - num2);
break;
case '*':
numStack.push(num1 * num2);
break;
case '/':
if (num2 == 0) {
throw "Division by zero";
}
numStack.push(num1 / num2);
break;
case '^':
numStack.push(pow(num1, num2));
break;
}
}
}
return numStack.top();
}
std::string Calculator::infixToPrefix(std::string infixExp) {
// Реализация преобразования в префиксную запись
}
std::string Calculator::infixToPostfix(std::string infixExp) {
// Реализация преобразования в постфиксную запись
}
double Calculator::calculateExpression(std::string infixExp) {
std::string postfixExp = convertToRPN(infixExp);
return evaluateRPN(postfixExp);
}
Основная программа может выглядеть следующим образом:
#include <iostream>
#include "Calculator.h"
int main() {
std::string infixExp = "2+3*4";
Calculator calculator;
try {
// Преобразование в постфиксную запись
std::string postfixExp = calculator.infixToPostfix(infixExp);
std::cout << "Postfix expression: " << postfixExp << std::endl;
// Преобразование в префиксную запись
std::string prefixExp = calculator.infixToPrefix(infixExp);
std::cout << "Prefix expression: " << prefixExp << std::endl;
// Вычисление выражения
double result = calculator.calculateExpression(infixExp);
std::cout << "Result: " << result << std::endl;
}
catch (const char* errorMessage) {
std::cout << "Error: " << errorMessage << std::endl;
}
return 0;
}
В этом примере основная программа создает объект Calculator, затем преобразует арифметическое выражение в постфиксную и префиксную форму, вычисляет результат и выводит его. Если возникает ошибка деления на ноль, она обрабатывается с помощью блока try-catch. Вы можете добавить обработку других аномальных ситуаций внутри класса Calculator или в основной программе при необходимости.