算术表达式的求解 问题描述:给定一个答案很大的算术表达式,通过c语言程序编出代码求出最后的结果。 基本要求: 1. 从键盘输入要求解的算术表达式: 2.采用栈结构进行算术表达式的求解过程;.能够判断算术表达式正确与否: 4.对于错误表达式给出提示; 5.对于正确的表达式给出最后的结果;
时间: 2024-03-19 10:46:04 浏览: 58
好的,下面是一个简单的 C 语言程序,用于实现算术表达式的求解。它可以满足你提出的基本要求。
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_SIZE 100 // 定义栈的最大容量
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
void push(Stack *s, char ch) {
if (s->top == MAX_SIZE - 1) {
printf("栈已满,无法入栈!\n");
exit(1);
}
s->data[++(s->top)] = ch;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("栈已空,无法出栈!\n");
exit(1);
}
return s->data[(s->top)--];
}
char peek(Stack *s) {
if (s->top == -1) {
printf("栈已空,无法取栈顶元素!\n");
exit(1);
}
return s->data[s->top];
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_digit(char ch) {
return isdigit(ch) || ch == '.';
}
int is_operator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
int priority(char ch) {
if (ch == '*' || ch == '/') {
return 2;
} else if (ch == '+' || ch == '-') {
return 1;
} else {
return 0;
}
}
double calculate(char op, double num1, double num2) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
double evaluate_expression(char *expr) {
Stack op_stack, num_stack;
init(&op_stack);
init(&num_stack);
int i = 0;
while (expr[i] != '\0') {
if (expr[i] == ' ') {
i++;
continue;
}
if (is_digit(expr[i])) {
double num = atof(&expr[i]);
push(&num_stack, num);
while (is_digit(expr[i])) {
i++;
}
} else if (is_operator(expr[i])) {
while (!is_empty(&op_stack) && priority(peek(&op_stack)) >= priority(expr[i])) {
double num2 = pop(&num_stack);
double num1 = pop(&num_stack);
char op = pop(&op_stack);
double result = calculate(op, num1, num2);
push(&num_stack, result);
}
push(&op_stack, expr[i]);
i++;
} else {
printf("表达式包含非法字符!\n");
exit(1);
}
}
while (!is_empty(&op_stack)) {
double num2 = pop(&num_stack);
double num1 = pop(&num_stack);
char op = pop(&op_stack);
double result = calculate(op, num1, num2);
push(&num_stack, result);
}
if (is_empty(&num_stack)) {
printf("表达式错误!\n");
exit(1);
} else {
return pop(&num_stack);
}
}
int main() {
char expr[MAX_SIZE];
printf("请输入要求解的算术表达式:\n");
fgets(expr, MAX_SIZE, stdin);
expr[strlen(expr) - 1] = '\0'; // 去掉换行符
double result = evaluate_expression(expr);
printf("表达式的结果为:%f\n", result);
return 0;
}
```
在这个程序中,我们定义了一个 `Stack` 结构体,用于实现栈的操作。`init` 函数用于初始化栈,`push` 函数用于将元素入栈,`pop` 函数用于将元素出栈,`peek` 函数用于查看栈顶元素,`is_empty` 函数用于判断栈是否为空。
在 `evaluate_expression` 函数中,我们使用两个栈,一个用于存储运算符,一个用于存储数字。遇到数字时,我们将其转换为浮点数,并将其入数字栈;遇到运算符时,我们将其与运算符栈顶元素进行比较,如果优先级较低,则将数字栈顶的两个元素出栈,进行相应的运算,并将结果入数字栈;否则将其入运算符栈。最后,将剩余的运算符依次出栈,进行相应的运算。
如果表达式中包含非法字符或者表达式错误(比如除数为0),则程序会提示错误并退出。如果表达式正确,程序将输出表达式的结果。
希望这个程序能够帮到你!
阅读全文
相关推荐

















