描述在数学课上老师让小Tu计算一道混合运算的题目请你使用计算机程序帮助小Tu完成。要求:①加、减、乘、除四则运算②按照运算顺序计算输入描述一个四则运算+、-、、表达式结尾用等于号结束输出描述输出四则运算的结果按照运算顺序计算【包括括号】希望能用c++编写代码
以下是使用C++编写的代码实现:
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <vector>
// 判断运算符的优先级
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return 0;
}
// 计算两个操作数的结果
int calculate(int num1, int num2, char op) {
switch(op) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num1 / num2;
}
return 0;
}
// 将字符串表达式转换为后缀表达式
std::vector<std::string> convertToPostfix(std::string expression) {
std::stack<char> opStack;
std::vector<std::string> postfix;
std::istringstream iss(expression);
std::string token;
while (getline(iss, token, ' ')) {
if (token == "=") {
while (!opStack.empty()) {
postfix.push_back(std::string(1, opStack.top()));
opStack.pop();
}
break;
} else if (token == "(") {
opStack.push('(');
} else if (token == ")") {
while (!opStack.empty() && opStack.top() != '(') {
postfix.push_back(std::string(1, opStack.top()));
opStack.pop();
}
if (!opStack.empty() && opStack.top() == '(') {
opStack.pop();
}
} else if (token == "+" || token == "-" || token == "*" || token == "/") {
while (!opStack.empty() && opStack.top() != '(' && getPriority(token[0]) <= getPriority(opStack.top())) {
postfix.push_back(std::string(1, opStack.top()));
opStack.pop();
}
opStack.push(token[0]);
} else {
postfix.push_back(token);
}
}
return postfix;
}
// 计算后缀表达式的结果
int calculatePostfix(std::vector<std::string> postfix) {
std::stack<int> numStack;
for (std::string token : postfix) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
int result = calculate(num1, num2, token[0]);
numStack.push(result);
} else {
int num = std::stoi(token);
numStack.push(num);
}
}
return numStack.top();
}
int main() {
std::string expression;
getline(std::cin, expression);
std::vector<std::string> postfix = convertToPostfix(expression);
int result = calculatePostfix(postfix);
std::cout << result << std::endl;
return 0;
}
使用示例: 输入:
( 1 + 2 * 3 ) / 4 =
输出:
1
``
原文地址: http://www.cveoy.top/t/topic/iSg0 著作权归作者所有。请勿转载和采集!