机试练习题三

来源:互联网 发布:vscode css智能提示 编辑:程序博客网 时间:2024/06/05 07:52

 1.四则混合运算

input=“1+4*5-8/3”,output=19

#include <iostream>#include <stack>using namespace std;//不带括号的四则运算,如果带括号,操作符的优先级就有'='//比较两个操作符的优先级char optCompare(char a,char b){if(a=='+' || a=='-'){if(b=='+' || b=='-'){return '>';}else{return '<';}}else{//如果a是*/,那么b无论是什么操作符,都是>return '>';}}int compute(int x,char optr,int y){int ret;switch(optr){case '+':ret=x+y;break;case '-':ret=x-y;break;case '*':ret=x*y;break;case '/':ret=x/y;break;}return ret;}//测试栈/*int i,x;for(i=0;i<5;i++){cout<<"input "<<i<<" value:";cin>>x;test.push(x);//进栈}while(test.empty()==false){cout<<test.top()<<" ";//返回栈顶的元素test.pop();//删除栈顶元素}*/void main(){stack<int> dat;stack<char> optr;string str="1+4*5-8/3";for(int i=0;i!=str.size();i++){if(str[i]>='0' && str[i]<='9'){dat.push((int)str[i]-48);//将字符转成数字进栈}else{if(optr.empty()){optr.push(str[i]);}else{if(optCompare(optr.top(),str[i])=='<'){optr.push(str[i]);}else{int a=dat.top();dat.pop();int b=dat.top();dat.pop();dat.push(compute(b,optr.top(),a));optr.pop();optr.push(str[i]);}}}}while(optr.empty()==false){int a=dat.top();dat.pop();int b=dat.top();dat.pop();dat.push(compute(b,optr.top(),a));optr.pop();}cout<<"the result is "<<dat.top()<<endl;}
原创粉丝点击