c++输入算式计算结果
时间: 2023-06-17 10:06:03 浏览: 154
以下是一个简单的 C++ 程序,可以读入一个算式并计算结果:
```cpp
#include <iostream>
#include <stack>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string expression;
cout << "Enter an expression: ";
getline(cin, expression);
stack<int> operands;
stack<char> operators;
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == ' ') {
continue;
} else if (expression[i] >= '0' && expression[i] <= '9') {
string operand = "";
while (i < expression.length() && expression[i] >= '0' && expression[i] <= '9') {
operand += expression[i];
i++;
}
i--;
operands.push(stoi(operand));
} else if (expression[i] == '(') {
operators.push(expression[i]);
} else if (expression[i] == ')') {
while (!operators.empty() && operators.top() != '(') {
int op2 = operands.top();
operands.pop();
int op1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
int result;
if (op == '+') {
result = op1 + op2;
} else if (op == '-') {
result = op1 - op2;
} else if (op == '*') {
result = op1 * op2;
} else if (op == '/') {
result = op1 / op2;
}
operands.push(result);
}
operators.pop();
} else {
while (!operators.empty() && ((expression[i] == '*' || expression[i] == '/') ||
(operators.top() == '+' || operators.top() == '-'))) {
int op2 = operands.top();
operands.pop();
int op1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
int result;
if (op == '+') {
result = op1 + op2;
} else if (op == '-') {
result = op1 - op2;
} else if (op == '*') {
result = op1 * op2;
} else if (op == '/') {
result = op1 / op2;
}
operands.push(result);
}
operators.push(expression[i]);
}
}
while (!operators.empty()) {
int op2 = operands.top();
operands.pop();
int op1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
int result;
if (op == '+') {
result = op1 + op2;
} else if (op == '-') {
result = op1 - op2;
} else if (op == '*') {
result = op1 * op2;
} else if (op == '/') {
result = op1 / op2;
}
operands.push(result);
}
cout << "Result: " << operands.top() << endl;
return 0;
}
```
这个程序使用了两个栈,一个用于存储操作数,另一个用于存储操作符。遍历输入的算式字符串,如果是数字,则将其转换为整数并压入操作数栈;如果是左括号,则将其压入操作符栈;如果是右括号,则弹出操作符栈中的操作符和操作数栈中的操作数进行计算,直到遇到左括号;如果是操作符,则弹出操作符栈中的操作符和操作数栈中的操作数进行计算,直到操作符栈为空或者栈顶操作符的优先级小于等于当前操作符的优先级。最终,操作数栈中剩下的一个元素就是算式的结果。
阅读全文