С++
Створіть додаток для обчислення арифметичного виразу користувача.
Користувач вводить з клавіатури деякий арифметичний вираз. Вираз
може містити: (), +, -, *, /.
Додаток обчислює результат виразу з урахуванням дужок, пріоритетів.
Результат виводиться на екран. Наприклад, якщо користувач ввів:
5*2 + 1
Результат: 11
Якщо користувач ввів:
5 * (2+1)
Результат: 15
Ответы
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
bool hasHigherPrecedence(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return true;
else
return false;
}
int applyOperator(int operand1, int operand2, char op) {
switch (op) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
return 0;
}
}
int evaluateExpression(const string& expression) {
stack<int> operandStack;
stack<char> operatorStack;
for (char c : expression) {
if (c == ' ')
continue;
if (isdigit(c)) {
operandStack.push(c - '0');
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.empty() && operatorStack.top() != '(') {
char op = operatorStack.top();
operatorStack.pop();
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = applyOperator(operand1, operand2, op);
operandStack.push(result);
}
operatorStack.pop();
} else if (isOperator(c)) {
while (!operatorStack.empty() && operatorStack.top() != '(' && hasHigherPrecedence(operatorStack.top(), c)) {
char op = operatorStack.top();
operatorStack.pop();
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = applyOperator(operand1, operand2, op);
operandStack.push(result);
}
operatorStack.push(c);
}
}
while (!operatorStack.empty()) {
char op = operatorStack.top();
operatorStack.pop();
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = applyOperator(operand1, operand2, op);
operandStack.push(result);
}
return operandStack.top();
}
int main() {
string expression;
cout << "Введите арифметическое выражение: ";
getline(cin, expression);
int result = evaluateExpression(expression);
cout << "Результат: " << result << endl;
return 0;
}