用c++编写算术表达式,输入一个表达式,表达式必合法,包括+、-、*、/、(、),输出这个表达式的值
时间: 2023-11-08 08:38:58 浏览: 42
要用C++编写一个能够计算算术表达式的程序,可以使用逆波兰表达式来实现。逆波兰表达式也被称为后缀表达式,它将运算符放在操作数的后面。
下面是一个示例程序,可以实现输入一个合法的算术表达式,并计算其值:
```cpp
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int performOperation(char operation, int operand1, int operand2) {
if (operation == '+')
return operand1 + operand2;
else if (operation == '-')
return operand1 - operand2;
else if (operation == '*')
return operand1 * operand2;
else if (operation == '/')
return operand1 / operand2;
return 0;
}
int evaluateExpression(string expression) {
stack<int> operands;
for (char c : expression) {
if (c == ' ')
continue;
if (isdigit(c)) {
int operand = 0;
while (isdigit(c)) {
operand = operand * 10 + (c - '0');
c = expression[++i];
}
operands.push(operand);
} else if (isOperator(c)) {
int operand2 = operands.top(); operands.pop();
int operand1 = operands.top(); operands.pop();
int result = performOperation(c, operand1, operand2);
operands.push(result);
}
}
return operands.top();
}
int main() {
string expression;
cout << "输入一个合法的算术表达式: ";
getline(cin, expression);
int result = evaluateExpression(expression);
cout << "表达式的值为: " << result << endl;
return 0;
}
```
你可以运行这个程序并输入一个合法的算术表达式,它会输出表达式的值。请确保输入的表达式符合语法规则,且不包含任何非法字符。