思路:
四则运算中由于涉及到运算符的优先级,并不能从左往右计算,这里要应用栈的思想。创建两个数组栈,分别存放数字和运算符。遍历输入的字符串,如果是数字则依次放入到数字栈。如果是运算符,则需要与字符栈的栈顶运算符进行优先级的比较,如果比栈顶优先级高,则放入栈中,反正则取出数字栈的栈顶两个数字与字符栈的栈顶元素进行运算,并将运算结果放入数字栈。
代码
#include <stdio.h>
#include <string.h>
int Calculation(int a, char ch, int b);
void Frame(void);
int Compare(char ch);
int main(void) {
Frame();
return 0;
}
int Calculation(int a, char ch, int b) {
if (ch == '+') {
return a + b;
} else if (ch == '-') {
return a - b;
} else if (ch == '*') {
return a * b;
} else if (ch == '/') {
return a / b;
} else {
return 0;
}
}
void Frame(void) {
//定义一个存储数据的栈
int numberStack[100] = {0};
int numberTop = -1;
//定义一个存储符号的栈
char symbolStack[100] = {'#'};
int symbolTop = 0;
char str[100];
int flag = -1;
scanf("%s", str);
int x = 0;
int length = (int)strlen(str);
int i = 0;
while (i < length) {
if (str[i] >= '0' && str[i] <= '9') {
x = x * 10 + (str[i++] - '0');
flag = 1;
} else {
if (flag == 1) {
numberStack[++numberTop] = x;
x = 0;
flag = -1;
}
if (Compare(symbolStack[symbolTop]) < Compare(str[i])) {
symbolStack[++symbolTop] = str[i++];
} else {
int b = numberStack[numberTop--];
int a = numberStack[numberTop--];
numberStack[++numberTop] = Calculation(a, symbolStack[symbolTop], b);
symbolTop--;
if (str[i] == '#' && symbolTop == 0) {
break;
}
}
}
}
printf("%d", numberStack[numberTop]);
}
int Compare(char ch) {
if (ch == '#') {
return 0;
} else if (ch == '+' || ch == '-') {
return 1;
} else if (ch == '*' || ch == '/') {
return 2;
} else {
printf("你输入的有非法符号,请重新输入!");
return -1;
}
}