中缀表达式转后缀表达式
一、中缀表达式和后缀表达式的区别:
中缀表达式就是我们通常认知中的表达式,比如1+((2+3)*4)-5,这样的表达式虽然容易被人所理解,但是不容易被机器所识别,为此推出了后缀表达式。
后缀表达式又被叫做逆波兰表达式,逆波兰表达式不需要被括号所识别,且容易被机器识别。
二、中缀表达式转后缀表达式的过程:
我们随意的拟定一个中缀表达式,比如:1+5*(3+2)-4*5;
我们对中缀表达式进行一步一步转换,转换方式如下:
1,从左到右扫描中缀式,若碰到操作数,则把操作数放入后缀式中
2,如果碰到操作符,就将其优先级与操作符栈的栈顶操作符比较。
a. 若碰到左括号,则压入操作符栈
b. 若碰到右括号,则将操作符栈内的元素依次移入到后缀式中,直到左括号停止(括号中依然遵循c,d两条)。
c. 若操作符的优先级高于栈顶操作符,则压入操作符栈
d.若操作符的优先级等于或低于栈顶操作符,则将栈顶操作符移入到后缀式中,接着与操作符栈的下一个操作符比较,直到操作符高于,再将操作符压入到操作符栈中。
#include <stdio.h>
#include <string.h>
#include <math.h>
int orderSort(char ch) {
if (ch == '(' || ch == ')') {
return 0;
} else if (ch == '+' || ch == '-') {
return 1;
} else if (ch == '*' || ch == '/') {
return 2;
} else if (ch == '.') {
return 3;
} else {
return -1;
}
}
double Calculation(double a, double b, char ch) {
if (ch == '+') {
return a + b;
} else if (ch == '-') {
return b - a;
} else if (ch == '*') {
return a * b;
} else if (ch == '/') {
return b / a;
} else {
int count = 0;
int n = a;
while (n != 0) {
n /= 10;
count++;
}
return b + a * pow(10, -count);
}
}
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
char str[1000];
scanf("%s", str);
char stack01[1000];
int top01 = -1;
char stack02[1000];
int top02 = -1;
int i = 0;
int len = (int)strlen(str);
int count = 0;
for (int i = 0; i < len + count; i++) {
if (str[i] == '-' && i != 0 && str[i - 1] != '(') {
count++;
for (int j = len + count; j >= i + 1; j--) {
str[j] = str[j - 1];
}
str[i] = '+';
i++;
}
}
str[len + count + 1] = '\0';
printf("%s\n", str);
len = (int)strlen(str);
while (i < len) {
if ((str[i] >= '0' && str[i] <= '9') || str[i] == '-') {
stack01[++top01] = str[i++];
if (str[i] < '0' || str[i] > '9') {
stack01[++top01] = ' ';
}
} else if (str[i] == '(') {
stack02[++top02] = str[i++];
} else if (str[i] == ')') {
while (stack02[top02] != '(') {
stack01[++top01] = stack02[top02--];
stack01[++top01] = ' ';
}
top02--;
i++;
} else {
if (top02 == -1 || orderSort(str[i]) > orderSort(stack02[top02])) {
stack02[++top02] = str[i++];
} else {
while (orderSort(stack02[top02]) >= orderSort(str[i])) {
stack01[++top01] = stack02[top02--];
stack01[++top01] = ' ';
}
stack02[++top02] = str[i++];
}
}
}
while (top02 != -1) {
stack01[++top01] = stack02[top02--];
stack01[++top01] = ' ';
}
stack01[++top01] = '\0';
printf("%s\n", stack01);
double numstack[1000];
int top03 = -1;
i = 0;
double value = 0;
while (i < top01) {
if ((stack01[i] >= '0' && stack01[i] <= '9') || stack01[i] == '-') {
if (stack01[i] == '-') {
i++;
while (stack01[i] >= '0' && stack01[i] <= '9') {
value = value * 10 + (stack01[i] - '0');
value = -value;
i++;
}
}
while (stack01[i] >= '0' && stack01[i] <= '9') {
value = value * 10 + (stack01[i] - '0');
i++;
}
numstack[++top03] = value;
value= 0;
i++;
} else {
double a = numstack[top03--];
double b = numstack[top03--];
numstack[++top03] = Calculation(a, b, stack01[i]);
i = i + 2;
}
}
printf("%lf", numstack[0]);
return 0;
}