lalalala


私信TA

用户名:zhangshuo

访问量:151973

签 名:

像狗一样的学习,像绅士一样地玩耍。

等  级
排  名 6
经  验 30154
参赛次数 10
文章发表 201
年  龄 12
在职情况 学生
学  校 芜湖市第十一中学
专  业

  自我简介:

今日懒惰流下的口水,将会成为明日里伤心的泪水。

解题思路:





注意事项:





参考代码:

#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 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区