c语言求带括号的四则运算表达式,给出一份完整代码
时间: 2024-10-15 09:22:03 浏览: 33
在C语言中,处理带括号的四则运算表达式可以使用递归解析法,利用栈的数据结构来保存操作数和运算符。下面是一个简单的例子,使用了递归函数`calculate()`来解决这个问题。请注意,这个示例仅适用于包含加减乘除和小括号的简单算术表达式,对于更复杂的数学库或者需要支持浮点数、优先级判断等功能的情况,可能需要引入正则表达式或编译原理的知识。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TOKENS 100
typedef enum {
NUM,
OPAREN,
CPAREN,
PLUS,
MINUS,
TIMES,
DIVIDE
} Token;
char tokens[MAX_TOKENS][5];
int token_count = 0;
void tokenize(char *expression) {
int i = 0;
while (expression[i]) {
if (expression[i] >= '0' && expression[i] <= '9') {
tokens[token_count++] = "NUM";
do {
tokens[token_count - 1] += expression[i++];
} while (expression[i] >= '0' && expression[i] <= '9');
}
else if (expression[i] == '(') {
tokens[token_count++] = "OPAREN";
}
else if (expression[i] == ')') {
tokens[token_count++] = "CPAREN";
}
else if (expression[i] == '+' || expression[i] == '-' ||
expression[i] == '*' || expression[i] == '/') {
tokens[token_count++] = (expression[i] == '+') ? "PLUS" :
(expression[i] == '-') ? "MINUS" :
(expression[i] == '*') ? "TIMES" :
"DIVIDE";
i++;
}
else {
i++;
}
}
}
double calculate(char *expression) {
double result = atof(tokens[0]); // Start with the first number
for (int i = 1; i < token_count; i++) {
double op2;
char operator_ = tokens[i];
if (operator_[0] != 'N') { // It's an operator
op2 = atof(tokens[i + 1]);
switch (operator_) {
case 'PLUS':
result += op2;
break;
case 'MINUS':
result -= op2;
break;
case 'TIMES':
result *= op2;
break;
case 'DIVIDE':
if (op2 != 0)
result /= op2;
else
return -1; // Division by zero error
break;
default:
printf("Invalid operator: %s\n", tokens[i]);
return -1;
}
i++; // Skip the second operand
}
else { // It's a number
result = atof(tokens[i]);
}
}
return result;
}
int main() {
char expression[] = "((3+4)*5)-2";
tokenize(expression);
printf("Result: %.2f\n", calculate(expression));
return 0;
}
```
阅读全文