求C++计算器思路
求C++计算器思路
求C++计算器思路
求C++计算器思路
效果如图
代码如下
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 操作符优先级映射表
int getPriority(char op) {
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
else
return 0;
}
// 执行计算
double calculate(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 evaluateExpression(string expression) {
stack<double> operandStack;
stack<char> operatorStack;
for (int i = 0; i < expression.length(); i++) {
char c = expression[i];
if (isspace(c)) {
continue; // 忽略空格
} else if (isdigit(c)) {
string numStr;
while (i < expression.length() && (isdigit(expression[i]) || expression[i] == '.')) {
numStr += expression[i];
i++;
}
double operand = stod(numStr);
operandStack.push(operand);
i--; // 回退一个字符,以便下次循环正常处理
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.empty() && operatorStack.top() != '(') {
char op = operatorStack.top();
operatorStack.pop();
double operand2 = operandStack.top();
operandStack.pop();
double operand1 = operandStack.top();
operandStack.pop();
double result = calculate(operand1, operand2, op);
operandStack.push(result);
}
operatorStack.pop(); // 弹出'('
} else {
while (!operatorStack.empty() && getPriority(c) <= getPriority(operatorStack.top())) {
char op = operatorStack.top();
operatorStack.pop();
double operand2 = operandStack.top();
operandStack.pop();
double operand1 = operandStack.top();
operandStack.pop();
double result = calculate(operand1, operand2, op);
operandStack.push(result);
}
operatorStack.push(c);
}
}
while (!operatorStack.empty()) {
char op = operatorStack.top();
operatorStack.pop();
double operand2 = operandStack.top();
operandStack.pop();
double operand1 = operandStack.top();
operandStack.pop();
double result = calculate(operand1, operand2, op);
operandStack.push(result);
}
return operandStack.top();
}
int main() {
string expression;
cout << "输入表达式(支持 + - * / 和括号):";
getline(cin, expression);
double result = evaluateExpression(expression);
cout << "结果为:" << result << endl;
return 0;
}
简单的思路就是接受用户输入的表达式,解析其中的数字和操作符,并根据优先级进行计算,最后输出结果
不知道你这个问题是否已经解决, 如果还没有解决的话: