【编程题]算术表达式求值。演示程序和源程序已给出。用户从键盘输入一个算术表达式,数字都是十进制整型(必须支持负数),运算符支持+-/()。用c语言编写源程序中的double deal_exp (charexp)函数,对这个算术表达式求值,返回结果。不限制方法,你可以用“原始”的多遍日描字符串,也可以用先进一点的栈(本课程前面接触的栈都是操作系统提供给程序以实现局部变量定义和函数调用的,现在你需要自己创建并使用栈了)。为便于集中精力在功能方面,可以不用检查用户输入的合法性。.
时间: 2024-02-06 12:12:13 浏览: 29
以下是符合要求的 C 语言源代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// 栈的结构体定义
typedef struct Stack {
double *data;
int top;
int max_size;
} Stack;
// 创建一个新的栈
Stack *new_stack(int max_size) {
Stack *stack = (Stack *) malloc(sizeof(Stack));
stack->data = (double *) malloc(sizeof(double) * max_size);
stack->top = -1;
stack->max_size = max_size;
return stack;
}
// 判断栈是否为空
int is_empty(Stack *stack) {
return stack->top == -1;
}
// 判断栈是否已满
int is_full(Stack *stack) {
return stack->top == stack->max_size - 1;
}
// 入栈
void push(Stack *stack, double value) {
if (is_full(stack)) {
printf("Error: Stack is full!\n");
exit(1);
}
stack->data[++stack->top] = value;
}
// 出栈
double pop(Stack *stack) {
if (is_empty(stack)) {
printf("Error: Stack is empty!\n");
exit(1);
}
return stack->data[stack->top--];
}
// 获取栈顶元素
double peek(Stack *stack) {
if (is_empty(stack)) {
printf("Error: Stack is empty!\n");
exit(1);
}
return stack->data[stack->top];
}
// 判断是否为运算符
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 获取运算符的优先级
int get_priority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
// 对两个操作数进行运算
double calculate(double a, double b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) {
printf("Error: Divide by zero!\n");
exit(1);
}
return a / b;
default:
printf("Error: Invalid operator!\n");
exit(1);
}
}
// 对算术表达式求值
double deal_exp(char *exp) {
Stack *num_stack = new_stack(strlen(exp));
Stack *op_stack = new_stack(strlen(exp));
int i = 0;
while (exp[i] != '\0') {
if (isspace(exp[i])) {
i++;
continue;
}
if (isdigit(exp[i]) || exp[i] == '-') {
double num = 0;
int sign = 1;
if (exp[i] == '-') {
sign = -1;
i++;
}
while (isdigit(exp[i])) {
num = num * 10 + exp[i] - '0';
i++;
}
push(num_stack, sign * num);
} else if (is_operator(exp[i])) {
while (!is_empty(op_stack) && get_priority(peek(op_stack)) >= get_priority(exp[i])) {
double b = pop(num_stack);
double a = pop(num_stack);
char op = pop(op_stack);
double result = calculate(a, b, op);
push(num_stack, result);
}
push(op_stack, exp[i]);
i++;
} else {
printf("Error: Invalid character!\n");
exit(1);
}
}
while (!is_empty(op_stack)) {
double b = pop(num_stack);
double a = pop(num_stack);
char op = pop(op_stack);
double result = calculate(a, b, op);
push(num_stack, result);
}
double result = pop(num_stack);
free(num_stack->data);
free(num_stack);
free(op_stack->data);
free(op_stack);
return result;
}
int main() {
char exp[100];
printf("Please input an arithmetic expression:\n");
fgets(exp, 100, stdin);
double result = deal_exp(exp);
printf("The result is: %g\n", result);
return 0;
}
```