设计一个可以进行四则运算,包括括号,小数点,表达式的c++程序
时间: 2024-02-06 11:02:14 浏览: 65
下面是一个可以进行四则运算的C++程序,支持括号、小数点、表达式等:
```c++
#include <iostream>
#include <stack>
#include <string>
#include <cmath>
using namespace std;
bool isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
double applyOperator(double left, double right, char op) {
switch (op) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
if (right == 0) {
throw runtime_error("Divide by zero");
}
return left / right;
default:
throw invalid_argument("Invalid operator: " + string(1, op));
}
}
double calculate(string expr) {
stack<double> numStack;
stack<char> opStack;
int i = 0;
bool isNegative = false;
while (i < expr.length()) {
char ch = expr[i];
if (ch == ' ') {
i++;
continue;
}
if (ch == '-') {
if (i == 0 || expr[i - 1] == '(') {
isNegative = true;
i++;
continue;
}
}
if (isdigit(ch) || ch == '.') {
int j = i;
while (j < expr.length() && (isdigit(expr[j]) || expr[j] == '.')) {
j++;
}
string numStr = expr.substr(i, j - i);
double num = stod(numStr);
if (isNegative) {
num = -num;
isNegative = false;
}
numStack.push(num);
i = j;
} else if (ch == '(') {
opStack.push(ch);
i++;
} else if (ch == ')') {
while (!opStack.empty() && opStack.top() != '(') {
char op = opStack.top();
opStack.pop();
double right = numStack.top();
numStack.pop();
double left = numStack.top();
numStack.pop();
double result = applyOperator(left, right, op);
numStack.push(result);
}
if (!opStack.empty() && opStack.top() == '(') {
opStack.pop();
} else {
throw invalid_argument("Unmatched parentheses");
}
i++;
} else if (isOperator(ch)) {
while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(ch)) {
char op = opStack.top();
opStack.pop();
double right = numStack.top();
numStack.pop();
double left = numStack.top();
numStack.pop();
double result = applyOperator(left, right, op);
numStack.push(result);
}
opStack.push(ch);
i++;
} else {
throw invalid_argument("Invalid character: " + string(1, ch));
}
}
while (!opStack.empty()) {
char op = opStack.top();
opStack.pop();
if (op == '(') {
throw invalid_argument("Unmatched parentheses");
}
double right = numStack.top();
numStack.pop();
double left = numStack.top();
numStack.pop();
double result = applyOperator(left, right, op);
numStack.push(result);
}
return numStack.top();
}
int main() {
string expr = "2 * (3 + 4) - 5 / 2";
try {
double result = calculate(expr);
cout << expr << " = " << result << endl;
} catch (exception& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
```
其中,`isOperator`函数用于判断一个字符是否为运算符;`getPriority`函数用于获取运算符的优先级;`applyOperator`函数用于计算两个数之间的运算结果;`calculate`函数用于计算一个表达式的值。这个程序使用两个栈分别存储数值和运算符,并根据运算符的优先级来进行计算。
阅读全文