北理工10计算机复试上机

中缀表达式转后缀表达式并计算相应的值

注意:值可能为小数

#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
using namespace std; 

double cal(queue<string> su){
	stack<double> nums;
	while(!su.empty()){
		if('0' <= su.front()[0] && su.front()[0] <= '9'){//数字字符串转换 
		 	char ch[20];
			strcpy(ch, su.front().data());//char数组可直接给string类型赋值,反之不行,可以使用strcpy()函数结合string类型的data()方法 
		 	//char ch[20] = "2.34";
			nums.push(atof(ch));//atof()字符串转换浮点型数字 ,相应的还有atoi(),atol(),在<cstdlib>中 
			cout<<"进栈:"<<atof(ch)<<endl;
			su.pop();
		}else{//注意两个操作数的赋值是倒过来的 
			double b = nums.top();
			nums.pop();
			double a = nums.top();
			nums.pop();
			char c = su.front()[0]; 
			if(c == '+'){
				nums.push(a + b);
				cout<<"进栈:"<<a + b<<endl;
			}else if(c == '-'){
				nums.push(a - b);
				cout<<"进栈:"<<a - b<<endl;
			}else if(c == '*'){
				nums.push(a * b);
				cout<<"进栈:"<<a * b<<endl;
			}else{
				nums.push(a / b);
				cout<<"进栈:"<<a / b<<endl;
			}
			su.pop();
		}
	}
	
	return nums.top();
}
int main(int argc, char *argv[]) {
	map<char, int> m;
	m['+'] = 0;
	m['-'] = 0;
	m['*'] = 1;
	m['/'] = 1;
	string str;
	stack<char> s;
	queue<string> suffix; 
	int i;
	string temp;
	while(cin>>str){
		for(i = 0; i < str.size(); ++i){
			if('0' <= str[i] && str[i] <= '9'){
				temp = "";
				while(('0' <= str[i] && str[i] <= '9') || str[i] == '.'){//截取数字 
					
					temp += str[i]; 
					++i;
				}
				--i;//注意		
				cout<<temp<<" ";
				suffix.push(temp);		
			}else if(s.size() == 0 || str[i] == '('){
				s.push(str[i]);
			}else if(str[i] == ')'){
				temp = "a";//将单个字符转换成字符串:
				//法一:定义一个长度为1的字符串,然后直接替换第一个位置  
				//法二:将字符赋值给字符数组,char ch[2] = {c,0},第二个0为字符串结束符\0,再将字符数组赋值给字符串 
				//注意不能使用:"" + c; 
				while(!s.empty() && s.top() != '('){//注意 
					temp[0] = s.top();
					cout<<temp<<" ";
					suffix.push(temp);
					s.pop();
				}
				s.pop();//左括号舍弃 
			}else{
				if(m[str[i]] > m[s.top()] || s.top() == '('){
					s.push(str[i]);
				}else{
					temp = "a";
					while(!s.empty() && m[str[i]] <= m[s.top()]){
						temp[0] = s.top();
						cout<<temp<<" ";
						suffix.push(temp);
						s.pop();
					}
					s.push(str[i]);//注意,第一遍忘了放 
				}
			}
		}
		temp = "a";
		while(!s.empty()){
			temp[0] = s.top();
			cout<<temp<<" ";
			suffix.push(temp);
			s.pop();
		}
		cout<<endl;
		double re = cal(suffix);
		cout<<"结果是:";
		cout<<re<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值