机试练习题三

 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值