0
点赞
收藏
分享

微信扫一扫

【栈】计算器 C++

爱做梦的老巫婆 2022-04-02 阅读 100

栈 计算器 C++
输入:1+(3+2)(7^2+69)/(2)
输出:258

  • 在输入的字符串两端加上(),变成(1+(3+2)(7^2+69)/(2))
  • 定义两个栈:存放数字 stack s1;存放符号 stack s2;
  • 给运算符指定优先级:+ - 1级;* / 2级;^ 3级;其余0级
  • 当遇到运算符时,通过运算符的优先级,来判断是否优先运算
    while(lev(x) <= lev(s2.top()) ){
    calc();
    }
  • 当遇到)时,要一直把括号内的数据全部运算完毕
    while(s2.top()!=‘(’){
    calc();
    }
#include <bits/stdc++.h>
using namespace std;
stack <int> s1;
stack <char> s2;
int lev(char ch)
{
	if(ch=='+' || ch=='-'){
		return 1;
	}else if(ch=='*' || ch=='/'){
		return 2;
	}else if(ch=='^'){
		return 3;
	}else {
		return 0;
	}
}
void calc()
{
	int n1=s1.top();
	s1.pop();
	int n2=s1.top();
	s1.pop();
	char ch=s2.top();
	s2.pop();
	int res;
	switch (ch){
		case '+':
			res=n1+n2;
			s1.push(res);
			//cout<<s1.top()<<endl;
			break;
		case '-':
			res=n2-n1;
			s1.push(res);
			//cout<<s1.top()<<endl;
			break;
		case '*':
			res=n1*n2;
			s1.push(res); 
			//cout<<s1.top()<<endl;
			break;
		case '/':
			res=n2/n1;
			s1.push(res);
			//cout<<s1.top()<<endl;
			break;
		case '^':
			res=pow(n2,n1);
			s1.push(res);
			//cout<<s1.top()<<endl;
			break;
		default: 
			break;
	}
	return ;
}
int main()
{
	string exp;
	cin>>exp;
	exp='('+exp+')';
	int i;
	for(i=0;i<exp.length();i++){
		char x=exp[i];
		//cout<<x<<endl;
		if(x>='0' && x<='9'){
			int a=x-'0';
			int j=i+1;
			char y=exp[j];
			while(y>='0' && y<='9'){
				int b=y-'0';
				a=a*10+b;
				y=exp[++j];//!!!
			}	
			s1.push(a);
			i=j-1;
		}else if(x=='('){
			s2.push(x);
		}else if(x==')'){
			while(s2.top()!='('){//要把括号里的全部计算出来,不能是if 
				calc();
			}
			s2.pop();
		}else {
			//x是运算符 
			/*
			(2*3+1)
			遇到* ,*等级小于(, 不会进入while 
			*/
			while(lev(x) <= lev(s2.top()) ){
				calc();
			}
			s2.push(x);
		}
	}
	cout<<s1.top();
	return 0;
}
举报

相关推荐

0 条评论