输入一个字符串代表算式,进行计算,不用栈且使用CString类型代替string类型,支持小数和%,写成一个函数,输入为CString字符串,输出为double类型结果
时间: 2024-05-04 12:21:38 浏览: 8
可以使用逆波兰表达式求解来实现,具体步骤如下:
1. 将中缀表达式转换为后缀表达式(即逆波兰表达式)
2. 计算后缀表达式的值
具体实现如下:
```c++
// 判断一个字符是否是操作符
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
// 获取操作符的优先级(越高越优先)
int getPriority(char op) {
if (op == '*' || op == '/' || op == '%')
return 2;
else if (op == '+' || op == '-')
return 1;
else
return 0;
}
// 将中缀表达式转换为后缀表达式(逆波兰表达式)
CString infixToPostfix(CString infix) {
CString postfix; // 存储后缀表达式
stack<char> ops; // 存储操作符的栈
int len = infix.GetLength();
for (int i = 0; i < len; i++) {
char c = infix[i];
if (isdigit(c) || c == '.') { // 数字和小数点直接加入后缀表达式
postfix += c;
} else if (c == '%') { // 将百分号转换成除以100的形式
postfix += "/100";
} else if (isOperator(c)) { // 处理操作符
while (!ops.empty() && isOperator(ops.top()) && getPriority(ops.top()) >= getPriority(c)) {
postfix += ops.top();
ops.pop();
}
ops.push(c);
} else if (c == '(') { // 左括号直接加入栈中
ops.push(c);
} else if (c == ')') { // 右括号将栈中的操作符加入后缀表达式,直到遇到左括号
while (!ops.empty() && ops.top() != '(') {
postfix += ops.top();
ops.pop();
}
if (!ops.empty() && ops.top() == '(') {
ops.pop();
}
}
}
// 将栈中的操作符加入后缀表达式
while (!ops.empty()) {
postfix += ops.top();
ops.pop();
}
return postfix;
}
// 计算后缀表达式的值
double evaluatePostfix(CString postfix) {
stack<double> nums; // 存储操作数的栈
int len = postfix.GetLength();
for (int i = 0; i < len; i++) {
char c = postfix[i];
if (isdigit(c) || c == '.') { // 处理数字和小数点
double num = 0;
int dotPos = -1;
while (i < len && (isdigit(postfix[i]) || postfix[i] == '.')) {
if (postfix[i] == '.') {
dotPos = i;
} else {
num = num * 10 + (postfix[i] - '0');
}
i++;
}
if (dotPos != -1) {
num /= pow(10, i - dotPos - 1);
}
i--;
nums.push(num);
} else if (isOperator(c)) { // 处理操作符
double num2 = nums.top();
nums.pop();
double num1 = nums.top();
nums.pop();
switch (c) {
case '+':
nums.push(num1 + num2);
break;
case '-':
nums.push(num1 - num2);
break;
case '*':
nums.push(num1 * num2);
break;
case '/':
nums.push(num1 / num2);
break;
case '%':
nums.push(num1 * num2 / 100);
break;
}
}
}
return nums.top();
}
// 计算算式的值
double calculate(CString expr) {
CString postfix = infixToPostfix(expr);
return evaluatePostfix(postfix);
}
```
使用示例:
```c++
CString expr = "3.14*2+(10-2)/3%+4.5";
double result = calculate(expr);
cout << result << endl; // 输出 11.2767
```