算术表达式求值c语言代码
时间: 2024-08-13 18:05:08 浏览: 59
C语言:中缀算术表达式求值(栈 附答案).docx
在C语言中,计算算术表达式的求值通常涉及到递归或栈的数据结构,因为我们需要能够处理优先级、括号和多个操作数。这里是一个简单的示例,使用递归函数来解析和求值基本的算术表达式:
```c
#include <stdio.h>
#include <ctype.h>
// 定义操作符优先级
enum {
PLUS = 1,
MINUS = 2,
MUL = 3,
DIV = 4,
};
// 计算两个操作数的结果
double apply_operator(double op1, double op2, enum precedence prec) {
switch (prec) {
case PLUS:
return op1 + op2;
case MINUS:
return op1 - op2;
case MUL:
return op1 * op2;
case DIV:
// 需要处理除数为零的情况
if (op2 == 0) {
printf("Error: Division by zero is not allowed.\n");
return 0; // 或者抛出异常
}
return op1 / op2;
default:
return 0; // 非法操作符
}
}
// 解析并求值表达式
double evaluate_expression(char *expr) {
double result = 0;
enum precedence current_prec = 0;
bool negative = false;
char op;
for (char *token = expr; *token != '\0'; token++) {
if (isdigit(*token)) {
double num = 0;
while (isdigit(*token)) {
num = 10 * num + (*token - '0');
token++;
}
if (negative) {
num = -num;
negative = false;
}
result = apply_operator(result, num, current_prec);
current_prec = PLUS;
} else if (*token == '+' || *token == '-') {
op = *token;
token++;
if (op == '-') {
negative = true;
}
current_prec = MINUS;
} else if (*token == '*' || *token == '/') {
op = *token;
token++;
current_prec = op == '*' ? MUL : DIV;
} else if (*token == '(') {
result = evaluate_expression(token + 1);
if (*token++ != ')') {
printf("Error: Missing closing parenthesis.\n");
return 0;
}
}
}
// 最后可能的操作
result = apply_operator(result, 0, current_prec);
return result;
}
int main() {
char expression[] = "5 + 3 * (2 - 1)";
double result = evaluate_expression(expression);
if (result != 0) {
printf("The result of the expression is: %lf\n", result);
}
return 0;
}
```
阅读全文