#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define STACK_SIZE 100
typedef struct {
char data[STACK_SIZE];
int top;
} Stack;
void initialize_stack(Stack* stack) {
stack->top = -1;
}
int is_stack_empty(Stack* stack) {
return stack->top == -1;
}
void push(Stack* stack, char value) {
stack->data[++stack->top] = value;
}
char pop(Stack* stack) {
return stack->data[stack->top--];
}
char peek(Stack* stack) {
return stack->data[stack->top];
}
int is_operator(char ch) {
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^') {
return 1;
}
return 0;
}
int get_operator_precedence(char ch) {
if (ch == '+' || ch == '-') {
return 1;
} else if (ch == '*' || ch == '/') {
return 2;
} else if (ch == '^') {
return 3;
}
return 0;
}
void infix_to_postfix(char* infix, char* postfix) {
Stack stack;
initialize_stack(&stack);
int infix_length = strlen(infix);
int postfix_index = 0;
for (int i = 0; i < infix_length; i++) {
char ch = infix[i];
if (isalnum(ch)) { // 操作数
postfix[postfix_index++] = ch;
} else if (is_operator(ch)) { // 运算符
while (!is_stack_empty(&stack) && peek(&stack) != '(' &&
get_operator_precedence(ch) <= get_operator_precedence(peek(&stack))) {
postfix[postfix_index++] = pop(&stack);
}
push(&stack, ch);
} else if (ch == '(') { // 左括号
push(&stack, ch);
} else if (ch == ')') { // 右括号
while (!is_stack_empty(&stack) && peek(&stack) != '(') {
postfix[postfix_index++] = pop(&stack);
}
pop(&stack); // 弹出左括号
}
}
while (!is_stack_empty(&stack)) {
postfix[postfix_index++] = pop(&stack);
}
postfix[postfix_index] = '\0';
}
double evaluate_postfix(char* postfix) {
Stack stack;
initialize_stack(&stack);
int postfix_length = strlen(postfix);
for (int i = 0; i < postfix_length; i++) {
char ch = postfix[i];
if (isdigit(ch)) { // 操作数
double operand = ch - '0';
push(&stack, operand);
} else if (is_operator(ch)) { // 运算符
double operand2 = pop(&stack);
double operand1 = pop(&stack);
double result = 0.0;
switch (ch) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
case '^':
result = pow(operand1, operand2);
break;
}
push(&stack, result);
}
}
return pop(&stack);
}
int main() {
char infix[100];
char postfix[100];
printf("请输入中缀表达式: ");
fgets(infix, sizeof(infix), stdin);
infix[strcspn(infix, "\n")] = '\0';
infix_to_postfix(infix, postfix);
printf("后缀表达式: %s\n", postfix);
double result = evaluate_postfix(postfix);
printf("表达式结果: %.2lf\n", result);
return 0;
}
C语言实现简单多项式求解
于 2023-11-28 01:50:49 首次发布