#include <iostream>
#include <string>
#include <stack>
#include <sstream>
int getPriority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
double executeOperation(double operand1, double operand2, char op) {
switch (op) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
default: return 0.0;
}
}
double calculateExpression(const std::string& expression) {
std::stack<double> operands;
std::stack<char> operators;
std::istringstream iss(expression);
char token;
while (iss >> token) {
if (isdigit(token) || (token == '.')) {
double number;
iss.putback(token);
iss >> number;
operands.push(number);
} else if (token == '(') {
operators.push(token);
} else if (token == ')') {
while (!operators.empty() && operators.top() != '(') {
char op = operators.top();
operators.pop();
double operand2 = operands.top();
operands.pop();
double operand1 = operands.top();
operands.pop();
operands.push(executeOperation(operand1, operand2, op));
}
if (!operators.empty() && operators.top() == '(') {
operators.pop();
}
} else if (token == '+' || token == '-' || token == '*' || token == '/') {
while (!operators.empty() && getPriority(operators.top()) >= getPriority(token)) {
char op = operators.top();
operators.pop();
double operand2 = operands.top();
operands.pop();
double operand1 = operands.top();
operands.pop();
operands.push(executeOperation(operand1, operand2, op));
}
operators.push(token);
}
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
double operand2 = operands.top();
operands.pop();
double operand1 = operands.top();
operands.pop();
operands.push(executeOperation(operand1, operand2, op));
}
return operands.top();
}
int main() {
std::string expression;
std::cout << "请输入一个表达式(支持四则运算和括号): ";
std::getline(std::cin, expression);
try {
double result = calculateExpression(expression);
std::cout << "结果为: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "错误: " << e.what() << std::endl;
}
return 0;
}
共 7 条回复
............
奈斯
真好多了10排
?
感觉还不够
666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666