c语言实现任意个数之间的加减乘除混合运算
时间: 2024-01-25 12:02:08 浏览: 64
可以通过使用逆波兰表达式来实现任意个数之间的加减乘除混合运算。具体实现步骤如下:
1. 将中缀表达式转换为逆波兰表达式。
2. 逆波兰表达式求值。
下面是实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_SIZE 100
// 定义栈结构
typedef struct {
int top;
double data[MAX_SIZE];
} Stack;
// 初始化栈
void init(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int is_empty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// 入栈
void push(Stack *s, double value) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = value;
}
// 出栈
double pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
// 获取栈顶元素
double peek(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
// 运算符优先级比较
int priority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
// 中缀表达式转换为逆波兰表达式
void infix_to_postfix(char *infix, char *postfix) {
Stack s;
init(&s);
int i = 0, j = 0;
while (infix[i] != '\0') {
if (isdigit(infix[i])) {
postfix[j++] = infix[i++];
while (isdigit(infix[i])) {
postfix[j++] = infix[i++];
}
postfix[j++] = ' ';
} else if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/') {
while (!is_empty(&s) && peek(&s) != '(' && priority(peek(&s)) >= priority(infix[i])) {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
push(&s, infix[i++]);
} else if (infix[i] == '(') {
push(&s, infix[i++]);
} else if (infix[i] == ')') {
while (!is_empty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
if (!is_empty(&s) && peek(&s) == '(') {
pop(&s);
}
i++;
} else {
i++;
}
}
while (!is_empty(&s)) {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
postfix[j] = '\0';
}
// 计算逆波兰表达式的值
double evaluate_postfix(char *postfix) {
Stack s;
init(&s);
int i = 0;
while (postfix[i] != '\0') {
if (isdigit(postfix[i])) {
double value = 0;
while (isdigit(postfix[i])) {
value = value * 10 + (postfix[i++] - '0');
}
push(&s, value);
} else if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/') {
double b = pop(&s);
double a = pop(&s);
switch (postfix[i]) {
case '+':
push(&s, a + b);
break;
case '-':
push(&s, a - b);
break;
case '*':
push(&s, a * b);
break;
case '/':
push(&s, a / b);
break;
}
i++;
} else {
i++;
}
}
return pop(&s);
}
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Enter an infix expression: ");
fgets(infix, MAX_SIZE, stdin);
infix[strlen(infix) - 1] = '\0';
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
double result = evaluate_postfix(postfix);
printf("Result: %.2f\n", result);
return 0;
}
```
以上代码可以实现对任意个数之间的加减乘除混合运算的计算。
阅读全文