原题链接:表达式计算4
解题思路:
注意事项:
参考代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stack>
#include<cctype>
#include<iostream>
using namespace std;
struct node{
int count;
char opr;
};
stack<int>s2;
node s1[100];//操作符
char a[100];
int len,top=0,oprnum=0;
int first[130];//存储++*/的优先级
int com(int x,int y,char opr ){
int tmp;
switch(opr){
case '^':{tmp=(int)pow(x,y);break;}
case '*':{tmp=x*y;break;}
case '/':{tmp=x/y;break;}
case '+':{tmp=x+y;break;}
case '-':{tmp=x-y;break;}
}
return tmp;
}
int comput(){
stack<int>s3;
for(int i=1;i<=top;i++){
if(s1[i].opr==0)s3.push(s1[i].count);
else{
int x,y;
char opr=s1[i].opr;
x=s3.top();
s3.pop();
if(s3.empty()) s3.push(com(0,x,opr));
else{
y=s3.top();
s3.pop();
s3.push(com(y,x,opr));
}
}
}
return s3.top();
}
int main()
{
first['+']=first['-']=2;
first['*']=first['/']=3;
first['^']=4;
first['(']=1;//
first[')']=1;//其实这两个优先级没使用,括号单独处理的.
scanf("%s",a);
len=strlen(a);
a[len]='.';
int tmp=0;
bool f=false;
for(int i=0;i<len;i++){
if(a[i]>=48&&a[i]<=57){ //计算数字
f=true;
tmp=tmp*10+a[i]-'0';
if(i==len-1) s1[++top].count=tmp;
continue;
}
else{
if(f)s1[++top].count=tmp;; //遇到符号,前一个数字入栈
f=false;
tmp=0;
if(s2.empty())s2.push(a[i]);//空栈,符号直接入栈
else {
if(a[i]=='('){s2.push(a[i]);continue; }//左括号直接入栈
if(first[a[i]]>first[s2.top()])//高优先级直接入栈
s2.push(a[i]);
else{
if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'||a[i]=='^'){//<=的优先级先出栈计算,再入栈
while(!s2.empty()&&first[a[i]]<=first[s2.top()]&&s2.top()!='('){
s1[++top].opr=s2.top();
s2.pop();
++oprnum;
} //=-*/^结束
s2.push(a[i]);
}
if(a[i]==')'){//右括号,出栈到遇到左括号
while(!s2.empty()&&s2.top()!='('){
s1[++top].opr=s2.top();
s2.pop();
++oprnum;
} //)结束
if(!s2.empty()&&s2.top()=='(')s2.pop();
}
}//两种出战结束
}
}//符号处理结束
}
while(!s2.empty()){//输入完成后剩余两种栈处理
char opr=s2.top();
if(opr=='('||opr==')'){
s2.pop();
continue;
}
s1[++top].opr=s2.top();
s2.pop();
++oprnum;
}
printf("%d\n",comput());
return 0;
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复