题意:实现一个含有括号的计算式子的程序
思路:先从简单的问题分析入手,先去想如何计算一个没有括号的式子。我的思路是利用栈,将符号和它后面的数压入栈中,最后再弹出来求和即可。加入括号后,我的思路是从左到右遍历这个式子,把每对括号里面的式子看成一个单独的式子,这样整个式子的计算过程中,遇到左括号就跳到单独式子计算中去,然后返回括号内的计算值。
例如:
不含括号的式子:2+3∗4/5−6
压入栈中后从下往上的值为:+2, +3*4/5, -6。其中计算 +3 *4/5 可以在读取到乘号或除号后弹出前一个值然后和当前值进行相乘或相除。
含有括号的式子
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
char F[110];
int len;
int GetInt(int& a) //获取数字
{
int r = 0;
while(isdigit(F[a])){
r *= 10;
r += F[a]-'0';
a++;
}
return r;
}
int Calc(int& a)
{
int r = 0;
stack<int> stk;
int status = 1;
int tmp;
bool flag = false;
while(a < len){
if(isdigit(F[a])){
if(!flag && status == 1){
stk.push(GetInt(a));
}
else if(!flag && status == 2){
stk.push(GetInt(a)*(-1));
}
else if(!flag && status == 3){
stk.push(tmp*GetInt(a));
}
else if(!flag && status == 4){
stk.push(tmp/GetInt(a));
}
else if(flag && status == 1){
stk.push(Calc(a));
flag = false;
}
else if(flag && status == 2){
stk.push(Calc(a)*(-1));
flag = false;
}
else if(flag && status == 3){
stk.push(tmp*Calc(a));
flag = false;
}
else if(flag && status == 4){
stk.push(tmp/Calc(a));
flag = false;
}
}
else{
if(F[a] == '+'){
status = 1;
a++;
}
else if(F[a] == '-'){
status = 2;
a++;
}
else if(F[a] == '*'){
tmp = stk.top(); stk.pop();
status = 3;
a++;
}
else if(F[a] == '/'){
tmp = stk.top(); stk.pop();
status = 4;
a++;
}
else if(F[a] == '('){
flag = true;
a++;
}
else if(F[a] == ')'){
a++;
break;
}
}
}
//printf("\naaa:\n");
while(!stk.empty()){
int t = stk.top(); stk.pop();
r += t;
//printf("t= %d\n", t);
}
//printf("aaa\n");
//printf("r = %d\n\n", r);
return r;
}
int main()
{
scanf("%s", F);
len = strlen(F);
int a = 0;
printf("%d\n", Calc(a));
return 0;
}